그래프/BFS
BFS 스페셜 저지
4gats
2023. 3. 7. 14:37
https://www.acmicpc.net/problem/16940
16940번: BFS 스페셜 저지
올바른 순서는 1, 2, 3, 4와 1, 3, 2, 4가 있다.
www.acmicpc.net
인접 리스트에 간선을 넣은 순서에 따라서
BFS의 순서가 달라진다!
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
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> a[100000];
int parent[100000];
int ans[100000];
bool check[100000];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n - 1; i++)
{
int u, v;
cin >> u >> v;
u -= 1; v -= 1;
a[u].push_back(v);
a[v].push_back(u);
}
for (int i = 0; i < n; i++)
{
cin >> ans[i];
ans[i] -= 1;
}
queue<int> q;
q.push(0);
check[0] = true;
int m = 1;
for (int i = 0; i < n; i++)
{
//아직 BFS가 진행중인데 큐가 비었다
if (q.empty())
{
cout << 0 << '\n';
return 0;
}
int x = q.front();
q.pop();
//순서가 올바르지 않음
if (x != ans[i])
{
cout << 0 << '\n';
return 0;
}
int cnt = 0;
for (int y : a[x])
{
if (check[y] == false)
{
parent[y] = x;
cnt += 1; // 자식 개수
}
}
for (int j = 0; j < cnt; j++)
{
if (m + j >= n || parent[ans[m + j]] != x)
{
cout << 0 << '\n';
return 0;
}
q.push(ans[m + j]);
check[ans[m + j]] = true;
}
m += cnt;
}
cout << 1 << '\n';
return 0;
}
|
cs |