Seren dev's blog
article thumbnail

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

 

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

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

www.acmicpc.net

풀이

매우 간단한 문제다.

HashMap을 사용하여 소의 번호와 위치를 저장하고, map의 메서드를 사용하여 문제를 해결한다.

이미 있는 소의 경우, 소의 원래 위치와 현재 위치가 다른 경우 cnt에 1을 더하고, map.put() 메서드를 사용하여 현재 key에 해당하는 map의 엔트리의 값을 변경한다.

새로운 소의 경우, map에 (번호, 현재 위치)를 추가한다. 

 

코드

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

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int t = Integer.parseInt(br.readLine());
		HashMap<Integer, Integer> map = new HashMap<>();
		
		int cnt = 0;
		
		while (t-- > 0) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			
			int key = Integer.parseInt(st.nextToken());
			int value = Integer.parseInt(st.nextToken());
			
			// 이미 있는 소의 경우
			if (map.containsKey(key)) {
				if (map.get(key) != value) {
					cnt++;
					map.put(key, value);
				}
			}
			// 새로운 소인 경우
			else
				map.put(key, value);
		}
		
		System.out.println(cnt);
	}

}

다른 풀이 2

배열을 사용하여 풀 수도 있다.

이 때 배열을 -1로 초기화 한 다음, 새로운 소의 경우와 이미 있는 소의 경우를 처리한다.

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

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int t = Integer.parseInt(br.readLine());
		int[] arr = new int[11];
		Arrays.fill(arr, -1);
		
		int cnt = 0;
		
		while (t-- > 0) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			
			int key = Integer.parseInt(st.nextToken());
			int value = Integer.parseInt(st.nextToken());
			
			// 새로운 소인 경우
			if (arr[key] == -1) {
				arr[key] = value;
			}
			// 이미 있는 소의 경우
			else {
				if (arr[key] != value) {
					cnt++;
					arr[key] = value;
				}
			}
			
		}
		
		System.out.println(cnt);
	}

}
728x90
profile

Seren dev's blog

@Seren dev

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!