POJ 2762 —— Going from u to v or from v to u? 强连通+拓扑

原题:http://poj.org/problem?id=2762


题意:判断图中任意两点是否单连通;

思路:求强连通分量,缩点构建新图,然后进行拓扑排序,每次入度 = 0 的点只能有一个,如果多于一个则输出“No”;


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

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;
		}
	}
}

vector<int>G[maxn];
void suodian()
{
	memset(du, 0, sizeof du);
	for(int i = 1;i<=taj;i++)	G[i].clear();
	for(int i = 0;i<edgenum;i++)
	{
		int u = Belong[edge[i].from];
		int v = Belong[edge[i].to];
		if(u != v)
		{
			G[u].push_back(v);
			du[v]++;
		}			
	}
}

bool toposort()
{
	for(int k = 1;k<=taj;k++)
	{
		int cnt = 0;
		for(int i = 1;i<=taj;i++)
		{
			if(du[i] == 0)
			{
				du[i]--;
				cnt++;
				for(int t = 0;t<G[i].size();t++)
				{
					int v = G[i][t];
					du[v]--;
				}
			}
		}
		if(cnt > 1)
		return false;
	}
	return true;
}

int main()
{
	scanf("%d", &cas);
	while(cas--)
	{
		init();
		scanf("%d%d", &n, &m);
		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);
		}
		suodian();
		if(toposort())	printf("Yes\n");
		else	printf("No\n");
	}
	return 0;
}


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