比赛时候,建图建错了。大体算法想到了,不过很多细节都没想好。
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <queue> 5 #include <algorithm> 6 using namespace std; 7 int flag[101]; 8 int p[101][101]; 9 int o[101][101]; 10 int n,z; 11 void dfs(int x,int step) 12 { 13 int i; 14 if(z) return ; 15 for(i = 1; i <= n; i ++) 16 { 17 if(i == x) continue; 18 if(o[x][i]&&!flag[i]) 19 { 20 flag[i] = step%2 + 1; 21 dfs(i,step+1); 22 } 23 else if(o[x][i]&&flag[i]) 24 { 25 if(flag[i] != step%2 + 1) 26 { 27 z = 1; 28 return ; 29 } 30 } 31 } 32 return ; 33 } 34 int main() 35 { 36 int i,j; 37 while(scanf("%d",&n)!=EOF) 38 { 39 memset(flag,0,sizeof(flag)); 40 memset(p,0,sizeof(p)); 41 memset(o,0,sizeof(o)); 42 for(i = 1; i <= n; i ++) 43 { 44 for(;;) 45 { 46 scanf("%d",&j); 47 if(j == 0) break; 48 p[i][j] = 1; 49 } 50 } 51 for(i = 1;i <= n;i ++) 52 { 53 for(j = 1;j <= n;j ++) 54 { 55 if(!p[i][j]||!p[j][i]) 56 o[i][j] = o[j][i] = 1; 57 } 58 } 59 z = 0; 60 for(i = 1; i <= n; i ++) 61 { 62 if(!flag[i]) 63 { 64 flag[i] = 2; 65 dfs(i,0); 66 } 67 } 68 if(z) 69 printf("NO "); 70 else 71 printf("YES "); 72 } 73 return 0; 74 }