본문 바로가기
Algorithm Study/BaekJoon (JAVA)

백준 14467_소가 길을 건나간 이유 1_JAVA

by 창브로 2024. 4. 15.
728x90

https://www.acmicpc.net/problem/14467

 

14467번: 소가 길을 건너간 이유 1

3번 소는 위치 1, 0, 1에서 관찰되었으므로 길을 최소 두 번 건넜음을 확인할 수 있다. 4번 소도 길을 한 번 건넜으며, 나머지 소는 길을 건넌 기록이 확인되지 않는다.

www.acmicpc.net

import java.util.*;
import java.io.*;


public class Main {
    static int N;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int count = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();


        N = Integer.parseInt(br.readLine()); // 관찰 횟수

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int cow = Integer.parseInt(st.nextToken()); // 소 번호
            int location = Integer.parseInt(st.nextToken()); // 소의 위치

            if (map.containsKey(cow)) {
                if (map.get(cow) != location) {
                    map.replace(cow, location);
                    count++;
                }
            } else {
                map.put(cow, location);
            }

        }

        System.out.print(count);
    }
}

 

회고

- map을 자유롭게 다루도록 더 노력해야겠다.

- 푸는 법은 바로 생각이 났는데 map을 활용하는 것에 애를 먹었다.