https://www.acmicpc.net/problem/16947
16947번: 서울 지하철 2호선
첫째 줄에 역의 개수 N(3 ≤ N ≤ 3,000)이 주어진다. 둘째 줄부터 N개의 줄에는 역과 역을 연결하는 구간의 정보가 주어진다. 같은 구간이 여러 번 주어지는 경우는 없고, 역은 1번부터 N번까지 번호
www.acmicpc.net
N개의 정점과 N개의 간선으로 이루어져 있으면
사이클은 반드시 하나 밖에 없다
DFS로 사이클을 구하고!
BFS로 거리를 구하자! dist[v] = dist[u] + 1
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
|
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<int> a[3000];
int check[3000]; // 0: not visited, 1: visited, 2: cycle
int dist[3000];
// p에서 x로 간다!
int go(int x, int p) {
// -2: found cycle and not included
// -1: not found cycle
// 0~n-1: found cycle and start index
if (check[x] == 1) {
return x; // 사이클의 시작 index
}
check[x] = 1;
for (int y : a[x]) {
if (y == p) continue; //이전 정점과 같은 정점
int res = go(y, x);
if (res == -2) return -2;
if (res >= 0) {
check[x] = 2;
if (x == res) return -2;
else return res;
}
}
return -1;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int u, v;
cin >> u >> v;
//정점 0에서 부터 시작
u -= 1; v -= 1;
a[u].push_back(v);
a[v].push_back(u);
}
//DFS로 사이클 찾자
go(0, -1);
//BFS로 거리 구하자
queue<int> q;
//사이클을 모두 넣는다
for (int i = 0; i < n; i++) {
if (check[i] == 2) {
dist[i] = 0;
q.push(i);
}
else {
dist[i] = -1;
}
}
while (!q.empty()) {
int x = q.front(); q.pop();
for (int y : a[x]) {
if (dist[y] == -1) {
q.push(y);
dist[y] = dist[x] + 1;
}
}
}
for (int i = 0; i < n; i++) {
cout << dist[i] << ' ';
}
cout << '\n';
return 0;
}
|
cs |