#66-【Tarjan模板2】迷宫城堡

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82120138

Description

为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。

Input

输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。

Output

对于输入的每组数据,如果任意两个房间都是相互连接的,输出"Yes",否则输出"No"。

Sample Input

3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0

Sample Output

Yes
No

题意:给定一个有向图求是不是只有一个强连通分量。

#include <iostream>
#include <cstring>
#include <vector>

#define SIZE 10010

using namespace std;

int bcount, dfn[SIZE], low[SIZE], top, s[SIZE], dfstime;
vector<int> graph[SIZE];
bool instack[SIZE];

void init(int n) // ~初始化~
{
	unsigned int i;
	
	top = dfstime = 0;
	memset(instack, false, sizeof (instack));
	memset(dfn, -1, sizeof (dfn));
	bcount = 0;
	for (i = 1; i <= n; ++i)
	{
		graph[i].clear();
	}
	
	return;
}

void tarjan(int u) // ~Tarjan模板~
{
	int i, v;
	
	s[++top] = u;
	instack[u] = true;
	dfn[u] = low[u] = ++dfstime;
	for (i = 0; i < graph[u].size(); ++i)
	{
		v = graph[u][i];
		if (dfn[v] == -1)
		{
			tarjan(v);
			low[u] = min(low[u], low[v]);
		}
		else if (instack[v])
		{
			low[u] = min(low[u], dfn[v]);
		}
	}
	if (dfn[u] == low[u])
	{
		++bcount;
		do
		{
			v = s[top];
			--top;
			instack[v] = false;
		} while (u != v);
	}
	
	return;
}

int main(int argc, char** argv)
{
	int n, m, u, v, i;
	
	while ((~scanf("%d%d", &n, &m)) && ((m) || (n)))
	{
		init(n);
		while (m--)
		{
			scanf("%d%d", &u, &v);
			graph[u].push_back(v);
		}
		for (i = 1; i <= n; ++i)
		{
			if (dfn[i] == -1)
			{
				tarjan(i);
				if (bcount > 1) // 好了好了都不行了还干什么
				{
					break;
				}
			}
		}
		if (bcount == 1)
		{
			printf("Yes\n");
		}
		else
		{
			printf("No\n");
		}
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/82120138