- Notifications
You must be signed in to change notification settings - Fork 846
/
Copy path7.java
113 lines (100 loc) · 3.81 KB
/
7.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
importjava.util.*;
classPosition {
privateintx;
privateinty;
publicPosition(intx, inty) {
this.x = x;
this.y = y;
}
publicintgetX() {
returnthis.x;
}
publicintgetY() {
returnthis.y;
}
}
publicclassMain {
// 땅의 크기(N), L, R 값을 입력받기
publicstaticintn, l, r;
publicstaticinttotalCount = 0;
// 전체 나라의 정보(N x N)를 입력받기
publicstaticint[][] graph = newint[50][50];
publicstaticint[][] unions = newint[50][50];
publicstaticint[] dx = {-1, 0, 1, 0};
publicstaticint[] dy = {0, -1, 0, 1};
// 특정 위치에서 출발하여 모든 연합을 체크한 뒤에 데이터 갱신
publicstaticvoidprocess(intx, inty, intindex) {
// (x, y)의 위치와 연결된 나라(연합) 정보를 담는 리스트
ArrayList<Position> united = newArrayList<>();
united.add(newPosition(x, y));
// 너비 우선 탐색 (BFS)을 위한 큐 라이브러리 사용
Queue<Position> q = newLinkedList<>();
q.offer(newPosition(x, y));
unions[x][y] = index; // 현재 연합의 번호 할당
intsummary = graph[x][y]; // 현재 연합의 전체 인구 수
intcount = 1; // 현재 연합의 국가 수
// 큐가 빌 때까지 반복(BFS)
while (!q.isEmpty()) {
Positionpos = q.poll();
x = pos.getX();
y = pos.getY();
// 현재 위치에서 4가지 방향을 확인하며
for (inti = 0; i < 4; i++) {
intnx = x + dx[i];
intny = y + dy[i];
// 바로 옆에 있는 나라를 확인하여
if (0 <= nx && nx < n && 0 <= ny && ny < n && unions[nx][ny] == -1) {
// 옆에 있는 나라와 인구 차이가 L명 이상, R명 이하라면
intgap = Math.abs(graph[nx][ny] - graph[x][y]);
if (l <= gap && gap <= r) {
q.offer(newPosition(nx, ny));
// 연합에 추가하기
unions[nx][ny] = index;
summary += graph[nx][ny];
count += 1;
united.add(newPosition(nx, ny));
}
}
}
}
// 연합 국가끼리 인구를 분배
for (inti = 0; i < united.size(); i++) {
x = united.get(i).getX();
y = united.get(i).getY();
graph[x][y] = summary / count;
}
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
n = sc.nextInt();
l = sc.nextInt();
r = sc.nextInt();
for (inti = 0; i < n; i++) {
for (intj = 0; j < n; j++) {
graph[i][j] = sc.nextInt();
}
}
// 더 이상 인구 이동을 할 수 없을 때까지 반복
while (true) {
for (inti = 0; i < n; i++) {
for (intj = 0; j < n; j++) {
unions[i][j] = -1;
}
}
intindex = 0;
for (inti = 0; i < n; i++) {
for (intj = 0; j < n; j++) {
if (unions[i][j] == -1) { // 해당 나라가 아직 처리되지 않았다면
process(i, j, index);
index += 1;
}
}
}
// 모든 인구 이동이 끝난 경우
if (index == n * n) break;
totalCount += 1;
}
// 인구 이동 횟수 출력
System.out.println(totalCount);
}
}