https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5V61LqAf8DFAWu
<풀이>
1. 모든 도시 좌표에서 서비스 제공을 시작한다.
2. 각 좌표에서 시작해서 서비스 영역을 넓혀가며, 그 때 마다 이윤을 구하고 최댓값을 저장한다.
3. 결과를 출력한다.
<해법>
1. 각 좌표에서 서비스 영역을 넓혀가는 방법.
=> 각 좌표에서 넓혀지는 서비스 영역이, 2차원 배열에서 BFS를 이용해 4방향 탐색하는 방식과 비슷하다고 생각하였습니다. 따라서 저는 위 방법을 이용하여 구현하였습니다.
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
114
115
116
117
118
119
120
121
122
123
|
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct pos {
//좌표
int x, y;
};
//4방향
int di[] = { -1,0,1,0 };
int dj[] = { 0,1,0,-1 };
int N, M;
int map[20][20];
bool visited[20][20];
int res;
//범위 내에 있는지 판단
bool inner(int x, int y) {
if (x < 0 || y < 0 || x >= N || y >= N) {
return false;
}
return true;
}
int bfs(pos str) {
//초기화
memset(visited, false, sizeof(visited));
queue<pos> q;
q.push(str);
visited[str.x][str.y] = true;
int K = 0, cnt = 0, MAX = 0;
while (!q.empty()) {
int qsize = q.size();
K++;
//서비스 영역부분 탐색
for (int i = 0; i < qsize; i++) {
pos cur = q.front();
q.pop();
//집 개수 세기
if (map[cur.x][cur.y] == 1) {
cnt++;
}
//4방향 탐색
for (int j = 0; j < 4; j++) {
pos nxt = cur;
nxt.x += di[j];
nxt.y += dj[j];
if (!inner(nxt.x, nxt.y)) {
continue;
}
if (visited[nxt.x][nxt.y]) {
continue;
}
q.push(nxt);
visited[nxt.x][nxt.y] = true;
}
}
//이윤 계산
int profit = (cnt * M) - ((K * K) + (K - 1) * (K - 1));
//손해보지 않는 경우, 집 개수 계산
if (profit >= 0) {
if (cnt > MAX) {
MAX = cnt;
}
}
}
return MAX;
}
int main() {
int test_case;
int T;
cin >> T;
for (test_case = 1; test_case <= T; test_case++) {
//초기화
memset(map, 0, sizeof(map));
res = 0;
//입력
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> map[i][j];
}
}
//모든 좌표마다 탐색
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
pos str = { i,j };
int tmp = bfs(str);
if (tmp > res) {
res = tmp;
}
}
}
//출력
cout << "#" << test_case << " " << res << "\n";
}
return 0;
}
|
구현에 대해 알아볼 수 있는 문제였습니다.
'알고리즘 문제풀이 > SWEA' 카테고리의 다른 글
[C++] SWEA 1244 - 최대 상금 (0) | 2020.12.31 |
---|---|
[C++] SWEA 2112 - 보호 필름 (0) | 2020.05.19 |
[C++] SWEA 5656 - 벽돌 깨기 (0) | 2020.05.19 |
[C++] SWEA 5650 - 핀볼 게임 (0) | 2020.05.15 |
[C++] SWEA 5644 - 무선 충전 (0) | 2020.05.15 |