-
Notifications
You must be signed in to change notification settings - Fork 2
/
g.cpp
101 lines (94 loc) · 2.29 KB
/
g.cpp
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
/*
Solution: O(N + M)
BFS bash. One bfs to find distances from capital.
Another bfs from each node to find nodes able to be reached without action 2
Another bfs after taking action 2 once.
*/
#include <bits/stdc++.h>
using namespace std;
int N, M;
vector<int> graph[200000], rgraph[200000];
int dist[200000], vis[200000];
bool vis1[200000], vis2[200000], vis3[200000];
int ans[200000];
void bfs3(int x, int d){
queue<int> q;
q.push(x);
while(!q.empty()){
int id = q.front();
q.pop();
if(vis3[id]) continue;
vis3[id] = true;
ans[id] = min(ans[id], d);
for(int i : rgraph[id]){
if(dist[i] >= dist[id]) continue;
q.push(i);
}
}
}
void bfs2(int x, int d){
queue<int> q;
q.push(x);
while(!q.empty()){
int id = q.front();
q.pop();
if(vis2[id]) continue;
vis2[id] = true;
ans[id] = min(ans[id], d);
for(int i : rgraph[id]){
if(dist[i] >= dist[id]){
bfs3(i, d);
}else{
q.push(i);
}
}
}
}
void bfs1(){
queue<pair<int, int>> q;
q.push({0, 0});
while(!q.empty()){
int id = q.front().first, d = q.front().second;
q.pop();
if(vis1[id]) continue;
vis1[id] = true;
bfs2(id, d);
for(int i : graph[id]){
q.push({i, d+1});
}
}
}
int32_t main(){
int T; cin >> T;
while(T--){
cin >> N >> M;
for(int i = 0; i < N; i++){
vis[i] = vis1[i] = vis2[i] = vis3[i] = false;
ans[i] = 1e9;
graph[i].clear();
rgraph[i].clear();
}
for(int i = 0; i < M; i++){
int u, v; cin >> u >> v;
graph[u-1].push_back(v-1);
rgraph[v-1].push_back(u-1);
}
queue<pair<int, int>> q;
q.push({0, 0});
while(!q.empty()){
int id = q.front().first, d = q.front().second;
q.pop();
if(vis[id]) continue;
vis[id] = true;
dist[id] = d;
for(int i : graph[id]){
q.push({i, d+1});
}
}
bfs1();
for(int i = 0; i < N; i++){
cout << ans[i] << " ";
}
cout << endl;
}
}