http://acm.hdu.edu.cn/showproblem.php?pid=1269
3 3 1 2 2 3 3 1 3 3 1 2 2 3 3 2 0 0
Yes No
裸题,直接贴模板就好了。
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; const int N=100005;//注意数组要开的够大 int head[N] ,ip,index,cnt_tar,top,stack[N],dfn[N],low[N],m,n,ins[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[u],low[v]); } else if(ins[v]) low[u]=min(low[u],dfn[v]); } if(dfn[u]==low[u]) { cnt_tar++; 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)); for(i=1;i<=n;i++) { if(!dfn[i]) { tarjan(i); } } if(cnt_tar==1) printf("Yes\n"); else printf("No\n"); } int main() { int u,v; while(~scanf("%d%d",&n,&m)) { if(m==0&&n==0) break; memset(head,-1,sizeof(head)); ip=0; for(int i=0;i<m;i++) { scanf("%d%d",&u,&v); add(u,v); } solve(); } return 0; }