LuoguP2002 消息扩散 tarjan求scc

强颜欢笑 提交于 2019-12-01 06:12:05

模板,注意有个地方打错好多次了:

for(int j = 0;j < scc[i].size();j++)——是j++不是i++!!!

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<vector>
 5 using namespace std;
 6 
 7 const int Maxn = 100010; 
 8 
 9 int ind[Maxn],dfn[Maxn],low[Maxn],stack[Maxn],ins[Maxn],inscc[Maxn];
10 vector<int> scc[Maxn],g[Maxn];
11 int cntscc,cntv,n,m,top;
12 
13 void tarjan(int x){
14     dfn[x] = low[x] = ++cntv;
15     ins[x] = 1,stack[++top] = x;
16     for(int i = 0;i < g[x].size();i++){
17         int u = g[x][i];
18         if(!dfn[u])tarjan(u),low[x] = min(low[x],low[u]);
19         else if(ins[u])low[x] = min(low[x],dfn[u]);
20     }
21     if(dfn[x] == low[x]){
22         cntscc++; int y = -1;
23         while(y != x){
24             y = stack[top--];
25             ins[y] = 0;
26             inscc[y] = cntscc;
27             scc[cntscc].push_back(y);
28         }
29     }
30 }
31 
32 int main(){
33     cin >> n >> m;
34     for(int i = 1;i <= m;i++){
35         int x,y;
36         cin >> x >> y;
37         g[x].push_back(y);
38     }
39     for(int i = 1;i <= n;i++)if(!dfn[i])tarjan(i);
40     for(int i = 1;i <= cntscc;i++){
41         for(int j = 0;j < scc[i].size();j++){
42             int u = scc[i][j];
43             for(int k = 0;k < g[u].size();k++){
44                 int v = g[u][k];
45                 if(inscc[v] != i)ind[inscc[v]]++;
46             }
47         }
48     }
49     int ans = 0;
50     for(int i = 1;i <= cntscc;i++)if(!ind[i])ans++;
51     cout << ans;
52 return 0;
53 }
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!