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數組遞減的順序遍歷逆圖。 
*/


發佈了74 篇原創文章 · 獲贊 25 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章