-
Notifications
You must be signed in to change notification settings - Fork 1
/
scc.cpp
86 lines (71 loc) · 1.52 KB
/
scc.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
#include<bits/stdc++.h>
using namespace std;
#define mx 50005
vector<int>g[mx],rg[mx],path,newg[mx];
int visited[mx],scc[mx];
int numscc;
void dfs1(int s)
{
visited[s]=1;
for(int i=0; i<g[s].size(); i++)
{
int v=g[s][i];
if(visited[v]==0) dfs1(v);
}
path.push_back(s);
}
void dfs2(int s)
{
visited[s]=1;
scc[s]=numscc;
for(int i=0; i<rg[s].size(); i++)
{
int v=rg[s][i];
if(visited[v]==0) dfs2(v);
}
}
int main()
{
int n,m;
cin>>n>>m;//taking input number of edges and vertexes
int u,v;
while(m--)
{
cin>>u>>v;
g[u].push_back(v);//making orginal graph
rg[v].push_back(u); //making reverse graph
}
for(int i=1; i<=n; i++)
{
if(!visited[i])
{
dfs1(i);
}
}
reverse(path.begin(),path.end()); //making topological sort
for(int i=0; i<mx; i++)
{
visited[i]=0;
}
int co=0;
for(int i=0; i<path.size(); i++)
{
if(visited[path[i]]==0)
{ co++;
numscc=path[i];
dfs2(path[i]);
}
}
cout<<co<<endl; //number of strongly connected components
for(int i=1; i<=n; i++)
{
for(int j=0; j<g[i].size(); j++)
{
int v=g[i][j];
if(scc[i]!=scc[v])
{
newg[scc[i]].push_back(scc[v]); //making scc graph
}
}
}
}