-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path1683-planets And Kingdoms.cpp
97 lines (75 loc) · 1.49 KB
/
1683-planets And Kingdoms.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
// JAI BAJARANG BALI
// manitianajay45
// give me some sunshine, give me some rain , give me another chance to grow up once again....
// sab moh maya hai....
// kosaraju algo
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
ll n,m;
vector<bool> visited(200005,false);
vector<ll> graph[200005];
vector<ll> order;
vector<ll> graphr[200005];
ll an=0;
vector<ll> ans(200005,0);
void topo(ll v){
visited[v]=true;
for(auto u:graph[v]){
if(!visited[u]){
topo(u);
}
}
order.push_back(v);
}
void dfs(ll v){
visited[v]=true;
ans[v]=an;
for(auto u:graphr[v]){
if(!visited[u]){
dfs(u);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// ll n;
cin >> n>>m;
for (ll i = 0; i <m; i++)
{
ll u,v;
cin>>u>>v;
graph[u].push_back(v);
graphr[v].push_back(u);
}
for(ll i=1;i<=n;i++){
if(!visited[i]){
topo(i);
}
}
// cout<<"YES"<<endl;
visited.assign(n+1,false);
reverse(order.begin(),order.end());
// for(auto i:order){
// cout<<i<<" ";
// }
cout<<endl;
for(auto i:order){
// cout<<i<<" ";
if(!visited[i]){
an++;
dfs(i);
}
}
// cout<<endl;
// cout<<"YES"<<endl;
cout<<an<<endl;
for(ll i=1;i<=n;i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}