Skip to content

Commit 37cd5ee

Browse files
authored
[20251119] BOJ / G5 / 상어 초등학교 / 설진영
1 parent f1526cb commit 37cd5ee

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N;
7+
static int[][] board;
8+
static Map<Integer, Set<Integer>> likes = new HashMap<>();
9+
static int[] dr = {-1, 1, 0, 0};
10+
static int[] dc = {0, 0, -1, 1};
11+
12+
public static void main(String[] args) throws IOException {
13+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
14+
N = Integer.parseInt(br.readLine());
15+
board = new int[N][N];
16+
17+
int[] order = new int[N * N];
18+
for (int i = 0; i < N * N; i++) {
19+
StringTokenizer st = new StringTokenizer(br.readLine());
20+
int student = Integer.parseInt(st.nextToken());
21+
order[i] = student;
22+
Set<Integer> likeSet = new HashSet<>();
23+
for (int j = 0; j < 4; j++) {
24+
likeSet.add(Integer.parseInt(st.nextToken()));
25+
}
26+
likes.put(student, likeSet);
27+
}
28+
29+
for (int student : order) {
30+
placeSeat(student);
31+
}
32+
33+
System.out.println(calculateSatisfaction());
34+
}
35+
36+
static void placeSeat(int student) {
37+
int maxLikes = -1, maxEmpty = -1;
38+
int bestR = -1, bestC = -1;
39+
40+
for (int r = 0; r < N; r++) {
41+
for (int c = 0; c < N; c++) {
42+
if (board[r][c] != 0) continue;
43+
44+
int likeCnt = 0, emptyCnt = 0;
45+
for (int d = 0; d < 4; d++) {
46+
int nr = r + dr[d];
47+
int nc = c + dc[d];
48+
if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;
49+
if (board[nr][nc] == 0) emptyCnt++;
50+
else if (likes.get(student).contains(board[nr][nc])) likeCnt++;
51+
}
52+
53+
if (likeCnt > maxLikes ||
54+
(likeCnt == maxLikes && emptyCnt > maxEmpty) ||
55+
(likeCnt == maxLikes && emptyCnt == maxEmpty && (bestR == -1 || r < bestR || (r == bestR && c < bestC)))) {
56+
maxLikes = likeCnt;
57+
maxEmpty = emptyCnt;
58+
bestR = r;
59+
bestC = c;
60+
}
61+
}
62+
}
63+
64+
board[bestR][bestC] = student;
65+
}
66+
67+
static int calculateSatisfaction() {
68+
int total = 0;
69+
int[] satisfaction = {0, 1, 10, 100, 1000};
70+
71+
for (int r = 0; r < N; r++) {
72+
for (int c = 0; c < N; c++) {
73+
int student = board[r][c];
74+
int cnt = 0;
75+
for (int d = 0; d < 4; d++) {
76+
int nr = r + dr[d];
77+
int nc = c + dc[d];
78+
if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;
79+
if (likes.get(student).contains(board[nr][nc])) cnt++;
80+
}
81+
total += satisfaction[cnt];
82+
}
83+
}
84+
85+
return total;
86+
}
87+
}
88+
```

0 commit comments

Comments
 (0)