HDU 3594 Cactus(强连通)

思路:判断一个图是否为强连通并且每条边仅属于一个环,我们把边的判断转化为对点的记录,在tarjan的过程里用一个fa数组记录每个结点的父子关系,当我们发现一条回边的时候从这个点向fa回溯,给点++,如果大于一证明这个点同时属于两个环


#include<bits/stdc++.h>
using namespace std;
const int maxn = 20000+50;
int in0[maxn],out0[maxn];
vector<int>e[maxn];
int pre[maxn],lowlink[maxn],sccno[maxn],dfs_clock,scc_cnt,fa[maxn],vis[maxn];
int flag=0;
stack<int>s;
void dfs(int u)
{
	pre[u]=lowlink[u]=++dfs_clock;
	s.push(u);
	for(int i = 0;i<e[u].size();i++)
	{
		int v = e[u][i];
		if(!pre[v])
		{
			fa[v]=u;
			dfs(v);
			lowlink[u]=min(lowlink[u],lowlink[v]);
		}
		else if (!sccno[v])
		{
			lowlink[u]=min(lowlink[u],pre[v]);
			int tmp = u;
			while(fa[tmp]!=v)
			{
                vis[tmp]++;
				if(vis[tmp]>1)
				{
					flag=1;
					return;
				}
				tmp = fa[tmp];
			}
		}
	}
	if(lowlink[u]==pre[u])
	{
		scc_cnt++;
		for(;;)
		{
			int x = s.top();
			s.pop();
			sccno[x]=scc_cnt;
			if(x==u)break;
		}
	}
}
void find_scc(int n)
{
	dfs_clock = scc_cnt = 0;
	memset(sccno,0,sizeof(sccno));
	memset(pre,0,sizeof(pre));
	memset(fa,-1,sizeof(fa));
	memset(vis,0,sizeof(vis));
	for(int i = 1;i<=n;i++)
		if(!pre[i])
			dfs(i);
}

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		flag=0;
		int n;
		scanf("%d",&n);
		for(int i = 0;i<=n;i++)
			e[i].clear();
        int u,v;
		while(scanf("%d%d",&u,&v)!=EOF && u+v)
		{
			u++,v++;
			e[u].push_back(v);
		}
		find_scc(n);
		if(flag || scc_cnt!=1)
			puts("NO");
		else
			puts("YES");
	}
}


Description

1. It is a Strongly Connected graph. 
2. Each edge of the graph belongs to a circle and only belongs to one circle. 
We call this graph as CACTUS. 



There is an example as the figure above. The left one is a cactus, but the right one isn’t. Because the edge (0, 1) in the right graph belongs to two circles as (0, 1, 3) and (0, 1, 2, 3).

Input

The input consists of several test cases. The first line contains an integer T (1<=T<=10), representing the number of test cases. 
For each case, the first line contains a integer n (1<=n<=20000), representing the number of points. 
The following lines, each line has two numbers a and b, representing a single-way edge (a->b). Each case ends with (0 0). 
Notice: The total number of edges does not exceed 50000. 

Output

For each case, output a line contains “YES” or “NO”, representing whether this graph is a cactus or not. 

Sample Input

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

Sample Output

YES
NO


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值