알고리즘

백준 추월 (JAVA)

박카스마시며코딩 2022. 4. 22. 16:18

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

 

2002번: 추월

입력은 총 2N+1개의 줄로 이루어져 있다. 첫 줄에는 차의 대수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 대근이가 적은 차량 번호 목록이 주어지고, N+2째 줄부터 N개의 줄에는 영식이

www.acmicpc.net

 

저는 Map과 Set을 통해서 문제를 해결하였습니다.

Map을 통해서 해당 번호가 몇번째 인덱스에 있는지를 확인하고 0 ~ index까지 터널에서 나왔는지를 확인합니다.

나오지 않은 것이 있다면 추월한 것이기 때문에 result를 늘려주었습니다.

 

package BOJ.ETC;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

public class BOJ_2002 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        Map<String,Integer> map = new HashMap<>();
        Set<String> used = new HashSet<>();
        List<String> input = new ArrayList<>();
        for(int i = 0 ; i < n ; i++){
            String command = br.readLine();
            input.add(command);
            map.put(command,i);
        }
        int result = 0;
        for(int i = 0 ; i < n ; i++){
            String command = br.readLine();
            int index = map.get(command);
            for(int j = 0 ; j < index ; j++){
                if(!used.contains(input.get(j))){
                    result++;
                    break;
                }
            }
            used.add(command);
        }
        System.out.println(result);
    }
}