hdoj 3594 Cactus 【仙人掌图的判定】【有向图tarjan求SCC】



Cactus

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


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 3594 Cactus 【仙人掌图的判定】【有向图tarjan求SCC】_第1张图片


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
 

题意就不说了。。。

仙人掌图性质如下

1.没有横向边;

2.图中没有桥;

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


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

AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 20000+10
#define MAXM 50000+100
#define INF 10000000
using namespace std;
struct Edge
{
	int from, to, next;
}edge[MAXM];
int head[MAXN], edgenum;
int low[MAXN], dfn[MAXN];
int dfs_clock;
int scc_cnt;
int flag;
stack S;
bool Instack[MAXN];
int n;//点数 
void init()
{
	edgenum = 0;
	memset(head, -1, sizeof(head));
}
void addEdge(int u, int v)
{
	Edge E = {u, v, head[u]};
	edge[edgenum] = E;
	head[u] = edgenum++;
} 
void getMap()
{
	int a, b;
	while(scanf("%d%d", &a, &b), a||b)	addEdge(a, b); 
}
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++;
		for(;;)
		{
			v = S.top(); S.pop();
			Instack[v] = false;
			if(v == u) break;
		}
	}
}
void find_cut(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()
{
	if(scc_cnt == 1 && flag == 0)
	printf("YES\n");
	else
	printf("NO\n");
}
int main()
{
	int t;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%d", &n);
		init();
		getMap();
		find_cut(1-1, n-1);
		solve();
	}
	return 0;
}



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