소가 길을 건너간 이유 1

이윤설·2024년 5월 27일


import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int repeat = Integer.parseInt(br.readLine());
        List<List<Integer>> list = new ArrayList<>();

        for (int i = 0; i < repeat; i++) {
            String input = br.readLine();
            String[] split = input.split(" ");
            List<Integer> tempList = new ArrayList<>();

            for (String s : split) {
                tempList.add(Integer.valueOf(s));
            }
            list.add(tempList);
        }

        int count = 0;
        Set<Integer> record = new HashSet<>();

        for (int i = 0; i < list.size(); i++) {

            int startNum = list.get(i).get(0);
            int secondNum = list.get(i).get(1);

            if (record.contains(startNum)) {
                continue;
            }
            record.add(startNum);

            for (int j = i; j < list.size(); j++) {
                if (list.get(j).get(0) == startNum) {
                    if (list.get(j).get(1) != secondNum) {
                        secondNum = list.get(j).get(1);
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

    }
}

모범답안

public class Main_BOJ_14467_소가길을건너간이유1 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer stringTokenizer;

        Map<Integer, Integer> cows = new HashMap<>();
        int N = Integer.parseInt(br.readLine());
        int answer = 0;
        for(int i = 0 ; i < N ; i++){
            stringTokenizer = new StringTokenizer(br.readLine());
            int cowNum = Integer.parseInt(stringTokenizer.nextToken());
            int location = Integer.parseInt(stringTokenizer.nextToken());

            if(cows.containsKey(cowNum)){
                if(cows.get(cowNum) != location)
                    answer++;

            }
           cows.put(cowNum, location);
        }

        System.out.println(answer);
    }
}

HashMap을 이용하면 효율적으로 풀 수 있다.
소의 번호를 Key , 소의 위치를 Value 로 저장했다.
만약 map에 소의 번호가 이미 존재하면 value와 입력으로 주어진 위치가 다르면 answer++ 한다.

배운점

추후 작성 너무 졸려미쳐

profile
화려한 외면이 아닌 단단한 내면

0개의 댓글