C語言源碼: [cpp] #include<stdio.h> #include<string.h> #define maxsize 1010 int E[maxsize][maxsize]; char name[maxsize][100]; int indegree[maxsize]; int Stack[maxsize]; int top; int find(char a[]) { int i=0; while((i<top)&&(strcmp(a,name[i])!=0)) i++; return i; } int main() { int n,num,p,q,i,j,topS,k; char a[100],b[100]; scanf("%d",&n); while(n) { top=0; for(i=0;i<n;i++) { indegree[i]=0; for(j=0;j<n;j++) E[i][j]=0; } for(i=0;i<n;i++) { scanf("%s %s",a,b); p=find(a); if(p==top) strcpy(name[top++],a); q=find(b); if(q==top) strcpy(name[top++],b); E[p][q]=1; indegree[q]++; } topS=0; for(i=0;i<n;i++) if(indegree[i]==0) Stack[topS++]=i; k=topS; num=0; while(topS) { i=Stack[--topS]; num++; for(j=0;j<n;j++) { if(E[i][j]==1) { indegree[j]--; if(indegree[j]==0) Stack[topS++]=j; } } } if(k==1&&num==n) printf("Yes\n"); else printf("No\n"); scanf("%d",&n); } }