Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 백준
- 너비우선탐색
- 세그먼트트리
- 알고리즘문제해결전략
- BOJ
- BFS
- 백트래킹
- 다이나믹프로그래밍
- 동적계획법
- 완전탐색
- 분리집합
- 그리디
- 누적합
- 문자열
- acm
- Greedy
- 분할정복
- Algospot
- 알고스팟
- stack
- 유니온파인드
- priority_queue
- 이분탐색
- DFS
- 스택
- backtracking
- 종만북
- 재귀
- union-find
- DP
Archives
- Today
- Total
DAMPER's blog
16724. 피리 부는 사나이 본문
728x90
https://www.acmicpc.net/problem/16724
문제 설명
바닥에 쓰여진 방향대로만 움직일 수 있으며, 해당 방향으로 이동했을 때 이루어지는 사이클 또는 집합의 개수를 구하는 문제이다.
Union-Find 자료구조를 이용해서 문제를 풀 수 있다.
모든 node를 돌면서 해당 방향으로 움직였을 때의 위치를 이미 방문한 곳이라면 merge()를 통해 병합 후 다른 노드로 이동한다. 처음 방문한 곳이 아니라면 병합 후 해당 방향으로 이동한다.
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
|
#include <bits/stdc++.h>
using namespace std;
#define swap(a, b) (a)^=(b)^=(a)^=(b)
#define endl '\n'
#define int long long
using pii = pair<int, int>;
const double EPS = 1e-9;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
class DisjointSet
{
public:
vector<int> parent;
DisjointSet();
DisjointSet(int size)
{
parent.resize(size+1, 0);
for(int i=0;i<=size;i++)
parent[i] = i;
}
int find(int v)
{
if(parent[v] == v) return v;
return parent[v] = find(parent[v]);
}
bool merge(int u, int v)
{
u = find(u);
v = find(v);
if(u == v) return true;
if(u > v) parent[u] = v;
else parent[v] = u;
return false;
}
};
int32_t main()
{
cin.sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
string tmp;
vector<vector<int>> smp(n, vector<int>(m, 0));
for(int i=0;i<n;i++)
{
cin >> tmp;
for(int j=0;j<m;j++)
{
if(tmp[j] == 'R') smp[i][j] = 0;
else if(tmp[j] == 'L') smp[i][j] = 1;
else if(tmp[j] == 'D') smp[i][j] = 2;
else if(tmp[j] == 'U') smp[i][j] = 3;
}
}
vector<vector<bool>> check(n, vector<bool>(m, false));
DisjointSet DS(n*m);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(check[i][j] == false)
{
int y = i, x = j;
while(1)
{
check[y][x] = true;
int dir = smp[y][x];
int ny = y+dy[dir], nx = x+dx[dir];
//if(ny >= n || nx >= m || ny < 0 || nx < 0) break;
if(DS.merge(y*m+x, ny*m+nx) || check[ny][nx]) break;
y = ny;
x = nx;
}
}
}
}
int ans = -1;
for(int i=0;i<DS.parent.size();i++)
{
if(DS.find(DS.parent[i]) == i) ans++;
}
cout << ans;
return 0;
}
|
cs |
728x90
'Problem Solving > BOJ 문제풀이' 카테고리의 다른 글
13140. Hello World! (0) | 2022.01.13 |
---|---|
2162. 선분 그룹 (0) | 2022.01.09 |
9527. 1의 개수 세기 (0) | 2022.01.05 |
2342. Dance Dance Revolution (0) | 2022.01.04 |
4386. 별자리 만들기 (0) | 2022.01.03 |