
소들이 길을 건너간 횟수를 구하는 문제이다
소의 번호와 위치(0 또는 1)가 주어진다
같은 소가 위치가 바뀔 때 마다 카운트를 1씩 증가해야함
첫 줄에 관찰 횟수 N이 주어짐 N은 100 이하의 양의 정수
다음 N줄부터는 한 줄에 하나씩 관찰 결과(소의 번호와 위치 0, 1로 이루어짐)
//1. 소 번호, 위치 2차원 배열에 저장
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
records[i][0] = Integer.parseInt(st.nextToken());
records[i][1] = Integer.parseInt(st.nextToken());
}
//2. 소의 현재 위치 배열
int[] cowPos = new int[11];
Arrays.fill(cowPos, -1); //아직 확인 되지 않은 소는 -1로 초기화
for(int i = 0 ; i < N; i++) {
int cowNum = records[i][0];
int location = records[i][1];
//처음 보는 소라면 위치 저장
if(cowPos[cowNum] == -1) {
cowPos[cowNum] = location;
}
// 전에 봤던 소인데 위치가 다르다면? 위치 갱신
else if(cowPos[cowNum] != location) {
count++;
cowPos[cowNum] = location;
}
}
package Bronze;
import java.io.*;
import java.util.*;
public class No_14467 { //소가 길을 건너간 이유1
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[][] records = new int[N][2];
//1. 소 번호, 위치 2차원 배열에 저장
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
records[i][0] = Integer.parseInt(st.nextToken());
records[i][1] = Integer.parseInt(st.nextToken());
}
//2. 소의 현재 위치 배열
int[] cowPos = new int[11];
Arrays.fill(cowPos, -1); //아직 확인 되지 않은 소는 -1로 초기화
int count = 0;
for(int i = 0 ; i < N; i++) {
int cowNum = records[i][0];
int location = records[i][1];
//처음 보는 소라면 위치 저장
if(cowPos[cowNum] == -1) {
cowPos[cowNum] = location;
}
// 전에 봤던 소인데 위치가 다르다면? 위치 갱신
else if(cowPos[cowNum] != location) {
count++;
cowPos[cowNum] = location;
}
}
System.out.println(count);
}
}
문제를 풀고 나서 보니까 꼭 2차원 배열을 안써도 되는 것을 알았다
입력 받자마자 바로 소의 위치 배열과 비교해서 처리하면 메모리를 더 아깔 수 있을 것 같다