标签:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<string> 5 #include<algorithm> 6 #include<map> 7 using namespace std; 8 9 map<string,int>id; 10 int G[1005][1005]; 11 bool indegree[1005]; 12 int num; 13 14 bool toposort() 15 { 16 int cnt,i; 17 for(cnt=i=0;i<num;i++) 18 { 19 if(indegree[i]) 20 cnt++; 21 } 22 if(cnt!=num-1)return false; 23 return true; 24 } 25 26 int main() 27 { 28 //freopen("in.txt","r",stdin); 29 int n; 30 string s1,s2; 31 while(scanf("%d",&n),n) 32 { 33 num=0; 34 id.clear(); 35 memset(indegree,0,sizeof(indegree)); 36 memset(G,0,sizeof(G)); 37 for(int i=0;i<n;i++) 38 { 39 cin>>s1>>s2; 40 if(!id.count(s1)) 41 id[s1]=num++; 42 if(!id.count(s2)) 43 id[s2]=num++; 44 if(!G[id[s1]][id[s2]]) 45 indegree[id[s2]]=true; 46 G[id[s1]][id[s2]]=1; 47 } 48 bool ans=toposort(); 49 if(ans) 50 printf("Yes\n"); 51 else 52 printf("No\n"); 53 } 54 return 0; 55 } 56 57 58 /*判断图有唯一拓扑序列 59 #include<cstdio> 60 #include<iostream> 61 #include<cstring> 62 #include<string> 63 #include<algorithm> 64 #include<map> 65 using namespace std; 66 67 map<string,int>id; 68 int G[1005][1005]; 69 bool indegree[1005]; 70 int num; 71 int c[1005]; 72 73 bool dfs(int u) 74 { 75 c[u]=-1; 76 for(int v=0;v<num;v++) 77 { 78 if(G[u][v]) 79 { 80 if(c[v]<0)return false; 81 else if(!c[v]&&!dfs(v))return false; 82 } 83 } 84 c[u]=1; 85 return true; 86 } 87 88 bool toposort() 89 { 90 int flag; 91 int cnt,i; 92 memset(c,0,sizeof(c)); 93 for(cnt=i=0;i<num;i++) 94 { 95 if(indegree[i]==false) 96 flag=i; 97 else 98 cnt++; 99 } 100 if(cnt!=num-1)return false; 101 if(!dfs(flag))return false; 102 return true; 103 } 104 105 int main() 106 { 107 //freopen("in.txt","r",stdin); 108 int n; 109 string s1,s2; 110 while(scanf("%d",&n),n) 111 { 112 num=0; 113 id.clear(); 114 memset(indegree,0,sizeof(indegree)); 115 memset(G,0,sizeof(G)); 116 for(int i=0;i<n;i++) 117 { 118 cin>>s1>>s2; 119 if(!id.count(s1)) 120 id[s1]=num++; 121 if(!id.count(s2)) 122 id[s2]=num++; 123 if(!G[id[s1]][id[s2]]) 124 indegree[id[s2]]=true; 125 G[id[s1]][id[s2]]=1; 126 } 127 bool ans=toposort(); 128 if(ans) 129 printf("Yes\n"); 130 else 131 printf("No\n"); 132 } 133 return 0; 134 } 135 */
标签:
原文地址:http://www.cnblogs.com/homura/p/4728276.html