0
点赞
收藏
分享

微信扫一扫

hdoj Cactus 3594 (强连通分量)


Cactus


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1566    Accepted Submission(s): 723



Problem 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.





hdoj  Cactus  3594  (强连通分量)_#define



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


//题意:


给n个点,任意条边,问是否每一条边都只属于一个环。


 


仙人掌图性质如下


1.没有横向边;

2.图中没有桥;

3.每个点的反向边和low[v]值比dfn[u]小的子节点v的数量和小于2;


思路:直接按题意来,判断图是否是强连通图且没有边属于两个或两个以上个环。对于边u -> v,在更新v的low值后即v已经出现在u所在的SCC里面,若v的low值不等于它的深度优先数,那么可以判断u -> v属于不同的环。


#include<stdio.h>
#include<string.h>
#include<stack>
#include<vector>
#define N 20010
#define M 50100
#include<algorithm>
using namespace std;
struct zz
{
	int from;
	int to;
	int next;
}edge[M];
int head[N],edgenum;
int low[N];
int dfn[N],dfs_clock;
bool instack[N];
int scc_cnt,flag;
int n;
stack<int>s;
void add(int u,int v)
{
	zz E={u,v,head[u]};
	edge[edgenum]=E;
	head[u]=edgenum++;
}
void tarjan(int u,int fa)
{
	int v;
	low[u]=dfn[u]=++dfs_clock;
	s.push(u);
	instack[u]=true;
	for(int i=head[u];i!=-1;i=edge[i].next)
	{
		v=edge[i].to;
		if(!dfn[v])
		{
			tarjan(v,u);
			low[u]=min(low[u],low[v]);
		}
		else if(instack[v])
		{
			low[u]=min(low[u],dfn[v]);
			if(low[v]!=dfn[v])//一条边属于两个或两个以上的环
				flag=1;
		}
	}
	if(low[u]==dfn[u])
	{
		scc_cnt++;
		while(1)
		{
			v=s.top();
			s.pop();
			instack[v]=false;
			if(v==u)
				break;
		}
	}
}
void find(int l,int r)
{
	memset(low,0,sizeof(low));
	memset(dfn,0,sizeof(dfn));
	memset(instack,false,sizeof(instack));
	dfs_clock=scc_cnt=flag=0;
	for(int i=l;i<=r;i++)
		if(!dfn[i])
			tarjan(i,-1);
}
void solve()
{
	find(0,n-1);
	if(scc_cnt==1&&flag==0)
		printf("YES\n");
	else
		printf("NO\n");
}
int main()
{
	int t;
	int x,y;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		memset(head,-1,sizeof(head));
		edgenum=0;
		while(scanf("%d%d",&x,&y),x|y)
		{
			add(x,y);
		}
		solve();
	}
	return 0;
}


举报

相关推荐

0 条评论