強連通分支

求強連通分支的三種算法:

http://www.cnblogs.com/luweiseu/archive/2012/07/14/2591370.html

主要是tarjin算法,詳見

http://www.cnblogs.com/saltless/archive/2010/11/08/1871430.html

例外給出一個自己寫的最基本的強連通分支算法:

#include<iostream>
using namespace std;
int time;
int *f;
int *visit;
void dfs_visit(int i,int **a,int n){
	time = time +1;
	visit[i] = 1;
	for(int k = 0;k<n;k++){
		if(visit[k] == 0&&a[i][k] == 1)
			dfs_visit(k,a,n);
	}
	time = time+1;
	f[i] = time;
}
void dfs(int **a,int n){
	time = 0;
	for(int i = 0;i<n;i++)
		if(visit[i] == 0)
			dfs_visit(i,a,n);
}
void output_connect(int i,int **a,int n){
	visit[i] = 1;
	for(int k = 0;k<n;k++){
		if(visit[k] == 0&&a[i][k] == 1){
			cout<<k<<" ";
			dfs_visit(k,a,n);
		}
	}
	cout<<endl;
}
void dfs_t(int **a,int n,int *arr){
	for(int i = 0;i<n;i++)
		if(visit[arr[i]] == 0){
			cout<<arr[i]<<" ";
			output_connect(arr[i],a,n);
		}
}
void sift(int *a,int *f,int n,int pos){
	int child = 2*pos+1;
	int temp = a[pos];
	while(child<n){
		if(child<n-1&&f[a[child]]>f[a[child+1]])
			child++;
		if(f[temp]>f[a[child]])
		{
			a[pos] = a[child];
			pos = child;
			child = 2*child+1;
		}
		else
			break;
	}
	a[pos] = temp;
}
void heapsort(int *a,int *f,int n){
	for(int i = n/2;i>=0;i--)
		sift(a,f,n,i);
	for(int i = n-1;i>=0;i--)
	{
		int temp = a[0];
		a[0] = a[i];
		a[i] = temp;
		sift(a,f,i,0);
	}
}
void main(){
	cout<<"輸入頂點的個數:";
	int ver_num;
	cin>>ver_num;
	visit = new int[ver_num];
	f = new int[ver_num];
	for(int i = 0;i<ver_num;i++)
		visit[i] = 0;
	cout<<"請輸入圖的矩陣表示,有邊用1,無邊用0:"<<endl;
	int **a;
	a = new int *[ver_num];
	for(int i = 0;i<ver_num;i++)
		a[i] = new int[ver_num];
	for(int i = 0;i<ver_num;i++)
		for(int j = 0;j<ver_num;j++)
			cin>>a[i][j];
	dfs(a,ver_num);
	int *arr;
	arr = new int[ver_num];
	for(int i = 0;i<ver_num;i++)
		arr[i] = i;
	heapsort(arr,f,ver_num);
	for(int i = 0;i<ver_num;i++){
		for(int j = 0;j<i;j++)
		{
			int temp = a[i][j];
			a[i][j] = a[j][i];
			a[j][i] = temp;
		}
	}
	for(int i =0;i<ver_num;i++)
		visit[i] =0;
	cout<<"圖的連通分支的輸出如下:"<<endl;
	dfs_t(a,ver_num,arr);

}
点赞