-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapital.cpp
More file actions
78 lines (62 loc) · 1.41 KB
/
capital.cpp
File metadata and controls
78 lines (62 loc) · 1.41 KB
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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 100001;
vector<vector<int>> adjList (N);
vector<int> finDist (N, -1);
vector<int> dp (N);
vector<bool> visited (N, false);
void bfs () {
finDist[1] = 0;
queue<int> que;
que.push(1);
while (!que.empty()) {
int curr = que.front();
que.pop();
for (int i: adjList[curr]) {
if (finDist[i] == -1) {
finDist[i] = finDist[curr] + 1;
que.push(i);
}
}
}
}
void dfs (int node) {
visited[node] = true;
dp[node] = finDist[node];
for (int i: adjList[node]) {
if (!visited[i] && finDist[node] < finDist[i]) {
dfs(i);
}
if (finDist[node] < finDist[i]) {
dp[node] = min(dp[node], dp[i]);
} else {
dp[node] = min(dp[node], finDist[i]);
}
}
}
int main ()
{
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
adjList[i].clear();
finDist[i] = -1;
dp[i] = 0;
visited[i] = false;
}
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
adjList[x].push_back(y);
}
bfs();
dfs(1);
for (int i = 1; i <= n; i++) cout << dp[i] << " ";
cout << "\n";
}
}