tyvj 1111 舞会 用kosaruju算法求强联通分量的个数

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数组递减的顺序遍历逆图。 
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值