有向图强连通分量

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
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<stack>
using namespace std;
#define R register
#define ll long long
#define fo(i,a,b) for(R int (i)=(a);(i)<=(b);++(i))
using namespace std;
vector<int>a[100001];
int pre[100001],low[100001],sccno[100001];
int dfscnt=0,sccnt=0,n,m;
stack<int>s;
void dfs(int x)
{
pre[x]=low[x]=++dfscnt;
s.push(x);
R int siz=a[x].size()-1;
fo(i,0,siz)
{
R int to=a[x][i];
if(!pre[to])//没走过
{
dfs(to);
low[x]=min(low[x],low[to]);
}
else if(!sccno[to])//走过但是没有成强连通分量
low[x]=min(low[x],pre[to]);
}
if(pre[x]==low[x])//回到一开始的点
{
sccnt++;
while(1)
{
R int tmp=s.top();s.pop();
sccno[tmp]=sccnt;
if(tmp==x)break;
}
}
}
int main()
{
scanf("%d%d",&n,&m);
fo(i,1,m)
{
R int x,y;
scanf("%d%d",&x,&y);
a[x].push_back(y);
}
fo(i,1,n)
if(!pre[i])dfs(i);
return 0;
}
显示 Gitment 评论