🌞Algorithm/🔥Baekjoon

[Baekjoon] 6770_Absolutely Acidic

뿌야._. 2025. 8. 14. 10:33
문제(출처: https://www.acmicpc.net/problem/6770)

< Absolutely Acidic >

 

문제 풀이 

 

HashMap을 사용하여 빈도수를 구하고, 빈도수 순으로 정렬하여 차이가 큰 가장 높은 빈도를 가진 값 2개를 구한다.

 

my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

public class _6770_ { // Absolutely Acidic

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		int N = Integer.parseInt(bf.readLine());

		HashMap<Integer, Integer> map = new HashMap<>();

		for (int i = 0; i < N; i++) {
			int num = Integer.parseInt(bf.readLine());
			if (map.containsKey(num)) {
				map.replace(num, map.get(num) + 1);
			} else {
				map.put(num, 1);
			}
		}

		ArrayList<Integer> list = new ArrayList<>(map.keySet());
		Collections.sort(list, new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				if (map.get(o1) == map.get(o2)) {
					return o2 - o1;
				}
				return map.get(o2) - map.get(o1);
			}
		});

		int max = list.get(0), value = map.get(list.get(1)), min = list.get(1), diff = Math.abs(max - min);

		for (int i = 2; i < list.size(); i++) {
			if (map.get(list.get(i)) == value && Math.abs(max - list.get(i)) > diff) {
				diff = Math.abs(max - list.get(i));
				min = list.get(i);
			}
		}
		System.out.println(Math.abs(max - min));
	}
}
변수)
N : 측정값 개수
map : <측정값, 빈도수>
num : 측정값
list : HashMap key -> ArrayList
max, value, min, diff : 가장 높은 빈도를 가진 측정값, 빈도수, 두 번째로 높은 빈도를 가진 측정값, 측정값 간의 차이

 

측정값 개수를 입력받는다. 측정값 개수만큼 측정값을 입력받아 HashMap에 <측정값, 빈도수>로 저장한다. HashMap의 key값을 ArrayList로 저장하고 빈도수 기준 내림차순, 빈도수가 같다면 측정값 기준 내림차순으로 정렬한다.

 

가장 높은 빈도를 가진 측정값을 ArrayList의 0번째 값으로, 두 번째 높은 빈도를 가진 측정값을 ArrayList의 1번째 값으로 초기화 후 ArrayList의 2번째 값부터 탐색한다. 이때, ArrayList의 1번째 값의 빈도수와 같고, 측정값 간의 차이가 현재보다 크다면 값을 업데이트한다.

 

최종 측정값 간의 차이를 출력한다.



 

'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글

[Baekjoon] 8641_Sklep  (2) 2025.08.15
[Baekjoon] 31637_ダンス (Dance)  (2) 2025.08.13
[Baekjoon] 4865_Shortest Prefixes  (2) 2025.08.12
[Baekjoon] 9609_PSU Campuses  (1) 2025.08.11
[Baekjoon] 3443_Reaux! Sham! Beaux!  (4) 2025.07.30