URAL 1198 Jobbery (强连通分量Kosaraju)

#include <stdio.h>
#define MAX_MEMBERS 2000
int numOfMembers;
int call[MAX_MEMBERS + 1][MAX_MEMBERS + 1];//用做邻接矩阵
int visited[MAX_MEMBERS + 1];
int stack[MAX_MEMBERS + 1];
int top;
int SCCNumArray[MAX_MEMBERS + 1];
int numOfSCCs;
int inDegree[MAX_MEMBERS + 1];

void DFS1(int from){
	visited[from] = 1;
	int to;
	for (to = 1; to <= numOfMembers; to++)
		if (visited[to] == 0 && call[from][to] == 1)
			DFS1(to);
	//stack保存的是一个拓扑排序的反序
	top++;
	stack[top] = from;
}

void DFS2(int from, int SCCNum){
	SCCNumArray[from] = SCCNum;
	visited[from] = 1;
	int to;
	for (to = 1; to <= numOfMembers; to++)
		//第二次深搜的是逆向图call[to][from]
		if (visited[to] == 0 && call[to][from] == 1)
			DFS2(to, SCCNum);
}

void getSCCsByKosaraju(){
	int from;
	for (from = 1; from <= numOfMembers; from++)
		if (visited[from] == 0)
			DFS1(from);

	for (from = 1; from <= numOfMembers; from++)
		visited[from] = 0;

	while (top > 0){
		from = stack[top--];
		if (visited[from] == 0)
			DFS2(from, ++numOfSCCs);
	}
}

int main(){

	scanf("%d", &numOfMembers);
	int from, to;
	for (from = 1; from <= numOfMembers; from++)
		while (scanf("%d", &to) != EOF && to != 0)
			call[from][to] = 1;

	getSCCsByKosaraju();

	for (from = 1; from <= numOfMembers; from++)
		for (to = 1; to <= numOfMembers; to++)
			if (call[from][to] == 1 && SCCNumArray[from] != SCCNumArray[to])
				inDegree[ SCCNumArray[to] ]++;

	int source = 0;
	int SCCNumOfSource = 0;
	int SCCNum;
	for (SCCNum = 1; SCCNum <= numOfSCCs; SCCNum++)
		if (inDegree[SCCNum] == 0){
			if (++source > 1)
				break;
			SCCNumOfSource = SCCNum;
		}

	int member;
	if (source == 1)
		for (member = 1; member <= numOfMembers; member++)
			if (SCCNumArray[member] == SCCNumOfSource)
				printf("%d ", member);
	printf("0\n");

	return 0;
}


 

你可能感兴趣的:(强连通分量,Kosaraju,1198,ural,Jobbery)