-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly_Connected_Components.cpp
77 lines (66 loc) · 1.1 KB
/
Strongly_Connected_Components.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
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define mp make_pair
const int maxn=505*1001;
int n,m,Time;
vector <int> Color[maxn],in[maxn],out[maxn],V;
bool mark[maxn];
inline void input()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int v,u;
cin>>u>>v;
out[u].pb(v);
in[v].pb(u);
}
}
void DFS(int v)
{
mark[v]=true;
for(auto i:out[v])
if(!mark[i])
DFS(i);
V.pb(v);
}
void SFD(int v)
{
mark[v]=true;
Color[Time].pb(v);
for(auto i: in[v])
if(!mark[i])
SFD(i);
}
inline void SCC()
{
for(int i=1;i<=n;i++)
if(!mark[i])
DFS(i);
reverse(V.begin(),V.end());
memset(mark,0,sizeof(mark));
for(auto i : V)
if(!mark[i])
Time++,SFD(i);
}
inline void Print_Ans()
{
cout << "This graph has "<<Time<<" Strongly Conected Components"<<endl<<endl;
for(int i=1;i<=Time;i++)
{
cout<<"Strongly Conected Component "<<i<<" contains "<<Color[i].size()<<" vertices"<<endl<<"They are : ";
sort(Color[i].begin(),Color[i].end());
for(auto j: Color[i])
cout<<j<<" ";
cout<<endl;
}
}
int32_t main()
{
input();
SCC();
Print_Ans();
return 0;
}