HDU 1269 —— 迷宫城堡

原题:http://acm.hdu.edu.cn/showproblem.php?pid=1269


思路:即强连通分量的个数为1;


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 11000;
const int maxm = 110000;
int n, m;
int head[maxn], edgenum;
int DFN[maxn], Low[maxn], Stack[maxn], Belong[maxn];
bool Instack[maxn];
int Time, taj, top;

struct Edge
{
	int from, to, next;
}edge[maxm];

void add(int u, int v)
{
	edge[edgenum].from = u;
	edge[edgenum].to = v;
	edge[edgenum].next = head[u];
	head[u] = edgenum++;
}

void init()
{
	memset(head, -1, sizeof head);
	edgenum = 0;
	memset(DFN, -1, sizeof DFN);
	memset(Instack, false, sizeof Instack);
	Time = taj = top = 0;
}

void Tarjan(int u)
{
	DFN[u] = Low[u] = ++Time;
	Stack[top++] = u;
	Instack[u] = true;
	for(int i = head[u];i != -1;i = edge[i].next)
	{
		int v = edge[i].to;
		if(DFN[v] == -1)
		{
			Tarjan(v);
			Low[u] = min(Low[u], Low[v]);
		}
		else if(Instack[v] && Low[u] > DFN[v])
			Low[u] = DFN[v];
	}
	if(DFN[u] == Low[u])
	{
		taj++;
		while(1)
		{
			int now = Stack[--top];
			Instack[now] = false;
			Belong[now] = taj;
			if(now == u)
				break;
		}
	}
}

int main()
{
	while(~scanf("%d%d", &n, &m))
	{
		if(n == 0 && m == 0)	break;
		init();
		while(m--)
		{
			int u, v;
			scanf("%d%d", &u, &v);
			add(u, v);
		}
		for(int i = 1;i<=n;i++)
		{
			if(DFN[i] == -1)
			Tarjan(i);
		}
		if(taj == 1)	printf("Yes\n");
		else	printf("No\n");
	}		
	return 0;
}


你可能感兴趣的:(强连通)