http://new.tyvj.cn/Problem_Show.aspx?id=1111
//kosaruju算法,强连通量个数
#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<ctime>
#include<iostream>
#include<vector>
using namespace std;
const int maxn=201;
vector<int>G[maxn],Gt[maxn];
int t,n;
int post[maxn];
bool vis[maxn];
int cmp(int a,int b)//降序
{
return a>b;
}
void dfs(vector<int>*G,int u)
{
vis[u]=true;
for(int i=0;i<G[u].size();i++)
{
if(!vis[G[u][i]]) dfs(G,G[u][i]);
}
post[u]=++t;//结点u变黑时间
}
int dfsAll(vector<int>*G,int *order)//以order顺序dfs图G
{
memset(vis,0,sizeof(vis));
t=0;
int times=0;
for(int i=1;i<=n;i++) if(!vis[order[i]])
{
times++;
dfs(G,order[i]);
}
return times;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in1.txt","r",stdin);
#endif
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
while(scanf("%d",&j)==1 && j)
{//采用vector,保存点i所有连接的点,并不保存边的信息
G[i].push_back(j);
Gt[j].push_back(i);
}
}
int order[maxn];
for(i=1;i<=n;i++) order[i]=i;
dfsAll(G,order);
//for(i=1;i<=n;i++) printf("%d\n",post[i]);
for(i=1;i<=n;i++) order[post[i]]=post[i];
sort(order+1,order+n+1,cmp);
int ans=dfsAll(Gt,order);
printf("%d\n",ans);
//printf("%.2lf\n",(double)clock()/CLOCKS_PER_SEC);
return 0;
}
/* 建立post数组,点u变黑的时间为post[u],按照结束时间
递减的顺序遍历逆图。
深搜两次,第一次遍历原图,获得post数组;
第二次,以post数组递减的顺序遍历逆图。
*/
本文介绍使用Kosaraju算法计算图中强连通分量的数量,通过深搜两次实现,一次遍历原图获得post数组,另一次以post数组递减顺序遍历逆图。
2万+

被折叠的 条评论
为什么被折叠?



