http://acm.hdu.edu.cn/showproblem.php?pid=3594
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.
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).
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.
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
只要对tarjan算法非常了解才能够理解这么做。这个题需要很好的理解dfn和low两个数组的作用,如果low[u]!=dfn[u],则说明已经存在环,如果我们访问u点时发现low[u]!=dfn[u],则说明有一条边在两个环上了。
#include <cmath>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int N=100005;
int stack[N],head[N],low[N],dfn[N],ins[N];
int ip,cnt_tar,top,index,ok,m,n;
struct note
{
int to;
int next;
};
note edge[N];
void add(int u,int v)
{
edge[ip].to=v;edge[ip].next=head[u];head[u]=ip++;
}
void tarjan(int u)
{
int j,i,v;
dfn[u]=low[u]=++index;
stack[++top]=u;
ins[u]=1;
for(i=head[u];i!=-1;i=edge[i].next)
{
v=edge[i].to;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[v],low[u]);
}
else if(ins[v])
{
low[u]=min(low[u],dfn[v]);
if(low[v]!=dfn[v])
ok=1;
}
if(ok)return;
}
if(dfn[u]==low[u])
{
cnt_tar++;
/*if(cnt_tar)
ok=1;*/
do
{
j=stack[top--];
ins[j]=0;
}
while(j!=u);
}
}
void solve()
{
int i;
top=0,index=0,cnt_tar=0;
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
memset(ins,0,sizeof(ins));
memset(stack,0,sizeof(stack));
ok=0;
for(i=1;i<=n;i++)
{
if(!dfn[i])
{
tarjan(i);
}
}
}
int main()
{
int u,v,T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
m=0;
memset(head,-1,sizeof(head));
ip=0;
while(1)
{
scanf("%d%d",&u,&v);
if(u==0&&v==0)
break;
add(u+1,v+1);
m++;
}
m-=1;
solve();
// printf("ok=%d\n",ok);
// printf("cnt_tar=%d\n",cnt_tar);
if(ok==1||cnt_tar!=1)
{
printf("NO\n");
}
else
printf("YES\n");
}
return 0;
}