http://acm.hdu.edu.cn/showproblem.php?pid=3594
#include<iostream>
using namespace std;
#define N 20005
#define M 50005
int top;
int stack[N],index;
bool instack[N];
int belong[N];
bool h[N];
int dfn[N],low[N];
struct node{
int next,v;
node(){};
node(int a,int b){
next=a,v=b;
}
}E[M];
int head[N],NE;
void init(){
NE=0;top=0;index=0;
memset(head,-1,sizeof(head));
memset(instack,0,sizeof(instack));
memset(h,0,sizeof(h));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
}
void insert(int u,int v){
E[NE]=node(head[u],v);
head[u]=NE++;
}
bool tarjan(int u){
dfn[u]=low[u]=++index;
instack[u]=true;
stack[top++]=u;
int cn=0;
for(int i=head[u];i!=-1;i=E[i].next){
int v=E[i].v;
if(h[v]) return false;
if(!dfn[v]){
if(!tarjan(v)) return false;
if(low[v]>dfn[u]) return false;
if(low[v]<dfn[u]) cn++;
if(cn>=2) return false;
if(low[v]<low[u])
low[u]=low[v];
}
else if(instack[v]){
cn++;
if(cn>=2) return false;
if(dfn[v]<low[u])
low[u]=dfn[v];
}
}
h[u]=1;
return true;
}
int main(void){
int t,n,m;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
init();
int u,v;
while(scanf("%d%d",&u,&v),u||v){
u++;v++;
insert(u,v);
}
bool flag=tarjan(1);
if(flag){
for(int i=1;i<=n;i++)
if(!dfn[i]){
flag=0;
break;
}
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
详见 http://goo.gl/l1K1E 仙人掌图的三个性质