标签:
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
YES NO
#include<stdio.h> #include<string.h> #include<iostream> #include<queue> #include<string> #define INF 0xfffffff #define min(a,b) (a>b?b:a) using namespace std; int dfn[20005*3],low[20005*3],stack[20005*3],head[20005*3],ins[20005*3],belong[20005*3]; int cnt,top,time,n,taj,flag; struct s { int u,v,next; }edge[50005*3]; void add(int u,int v) { edge[cnt].u=u; edge[cnt].v=v; edge[cnt].next=head[u]; head[u]=cnt++; } void init() { memset(dfn,-1,sizeof(dfn)); memset(stack,0,sizeof(stack)); memset(low,-1,sizeof(low)); memset(head,-1,sizeof(head)); memset(ins,0,sizeof(ins)); memset(belong,-1,sizeof(belong)); cnt=top=time=taj=0; } void tarjan(int u) { dfn[u]=low[u]=time++; ins[u]=1; stack[top++]=u; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; if(dfn[v]==-1) { tarjan(v); low[u]=min(low[v],low[u]); } else { if(ins[v]) { low[u]=min(dfn[v],low[u]); if(dfn[v]!=low[v]) { flag=1; } } } } if(low[u]==dfn[u]) { int now; taj++; do { now=stack[--top]; ins[now]=0; if(belong[now]!=-1) flag=1; belong[now]=taj; }while(now!=u); } } int main() { int t; scanf("%d",&t); while(t--) { int a,b; scanf("%d",&n); init(); while(scanf("%d%d",&a,&b),a||b) { add(a,b); } flag=0; for(int i=0;i<n;i++) { if(dfn[i]==-1) tarjan(i); } if(taj==1&&flag==0) printf("YES\n"); else printf("NO\n"); } }
标签:
原文地址:http://blog.csdn.net/yu_ch_sh/article/details/43818559