Algorithm/Baekjoon
[Algorithm]Baekjoon 16724 :: 피리 부는 사나이
MaxLevel
2024. 2. 26. 17:45
https://www.acmicpc.net/problem/16724
16724번: 피리 부는 사나이
첫 번째 줄에 지도의 행의 수를 나타내는 N(1 ≤ N ≤ 1,000)과 지도의 열의 수를 나타내는 M(1 ≤ M ≤ 1,000)이 주어진다. 두 번째 줄부터 N개의 줄에 지도의 정보를 나타내는 길이가 M인 문자열이 주
www.acmicpc.net
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
|
using namespace std;
int n, m;
char operations[1001][1001];
int arr[1001][1001] = { 0 };
int dirs[4][2] = { {-1,0}, {1,0}, {0,-1}, {0,1} };
int parents[1000001] = { 0 };
int getParent(int node)
{
if (node == parents[node]) return node;
return parents[node] = getParent(parents[node]);
}
void unionParents(int a, int b)
{
a = getParent(a);
b = getParent(b);
if (a < b) parents[b] = a;
else parents[a] = b;
}
int convertToDirsIndex(char op)
{
switch (op)
{
case 'U': return 0;
case 'D': return 1;
case 'L': return 2;
case 'R': return 3;
default:
return -1000000;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin >> operations[i][j];
parents[m * i + j] = m * i + j;
arr[i][j] = m * i + j;
}
}
int answer = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
int dirsIndex = convertToDirsIndex(operations[i][j]);
int nextY = i + dirs[dirsIndex][0];
int nextX = j + dirs[dirsIndex][1];
int nextParent = arr[nextY][nextX];
unionParents(arr[i][j], arr[nextY][nextX]);
}
}
for (int i = 0; i < n * m; ++i)
{
if (i == parents[i]) ++answer;
}
cout << answer;
}
|
cs |
처음에 그냥 문제에 주어진 테스트케이스 하나만 보고서는 그냥 사이클 개수를 구하면 되는 줄 알았다.
틀리고나서 다른 테스트케이스 보고나서야 문제를 제대로 이해했다.
결론은 Union-Find이다. 즉, 연결된 칸들을 전부 하나의 집합으로 만들어버리는 것이다.
유난히 class5문제에는 Union-Find를 이용하는 문제가 많은 것 같다. 그만큼 중요하다는 뜻인가?
어쨌든 parents를 0부터 n*m-1까지, 즉 배열의 크기에 맞게 만들어주고, 0,0부터 n,m까지 순회하면서 해당 i,j에 맞는 명령어칸의 ('D'면 arr[i+1][j] ) 번호와 union해주면 된다.
전부 업데이트 했다면 parents를 순회하면서 i == parents[i]인 경우 answer를 카운팅해주면 된다.
i == parents[i]라는 것은 해당 i가 집합의 root라는것을 의미한다. 이 root의 개수를 카운팅해주는 것이다.