Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

强连通分量——Tarjan算法

$
0
0
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_SIZE = 100;
int G[MAX_SIZE][MAX_SIZE];
bool isInStack[MAX_SIZE];
int DFN[MAX_SIZE];
int LOW[MAX_SIZE];
int STACK[MAX_SIZE];
int NUM;
int COUNT;
int STEP;
int V;

void init(){
	V = 10;
	COUNT = 0;
	STEP = 0;
	NUM = 0;
	memset( isInStack, false, sizeof( isInStack ) );
	memset( STACK, 0, sizeof( STACK ) );
	memset( DFN, 0, sizeof( DFN ) );
	memset( LOW, 0, sizeof( LOW ) );
	memset( G, 0, sizeof( G ) );
	/*
	G[1][2] = G[1][3] = G[2][4] = G[3][4] =
	G[3][5] = G[4][1] = G[4][6] = G[5][6] = 1;
	*/
	G[1][3] = G[1][10] = G[2][1] = G[2][3] =  
    G[2][4] = G[3][5] = G[4][5] = G[4][6] =  
    G[5][3] = G[5][7] = G[6][4] = G[6][7] =  
    G[7][7] = G[8][9] = G[9][8] = G[10][2] = 1;  
}

void tarjan( int index ){
	DFN[index] = LOW[index] = ++COUNT;
	isInStack[index] = true;
	STACK[++STEP] = index;
	for( int i = 1; i <= V; ++i ){
		if( G[index][i] && !DFN[i] ){
			tarjan( i );
			if( LOW[index] > LOW[i] ) LOW[index] = LOW[i];
		}
		else if( G[index][i] && isInStack[i] && DFN[i] < LOW[index] ){
			LOW[index] = DFN[i];
		}
	}
	if( DFN[index] == LOW[index] ){
		NUM++;
		cout<<"SCC "<<NUM<<" : "<<endl;
		int i;
		do{
			i = STACK[STEP--];
			isInStack[i] = false;
			cout<<i<<"	";
		}while( index != i );
		cout<<endl;
	}
}

void solve(){
	init();
	for( int i = 1; i <= V; ++i ){
		if( !DFN[i] ) tarjan(i);
	}
}


int main(int argc, _TCHAR* argv[]){
	solve();
	system("pause");
	return 0;
}

作者:u011659057 发表于2013-12-3 2:53:25 原文链接
阅读:110 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>