hdu3342: http://acm.hdu.edu.cn/showproblem.php?pid=3342
题意:判断是否有环,无环输出YES,有环输出NO 解法:dfs
code:
#include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> using namespace std; int v[150][150],c[150],n,m; bool dfs(int k) { c[k]=-1; for(int i=0;i<n;i++) { if(v[k][i]) { if(c[i]==-1)return false; else if(!c[i]&&!dfs(i))return false; } } c[k]=1; return true; } int main() { int x,y,i; while(1) { scanf("%d%d",&n,&m); if(n==0) break; memset(v,0,sizeof(v)); memset(c,0,sizeof(c)); for(i=0;i<m;i++) { scanf("%d%d",&x,&y); v[x][y]=1; } for(i=0;i<n;i++) { if(c[i]==0&&!dfs(i)) { printf("NO\n"); break; } } if(i==n) printf("YES\n"); } } /* input: 3 2 0 1 1 2 2 2 0 1 1 0 0 0 output: YES NO */