题意:给出n,m,人的编号为 0到n-1,再给出m个关系,问能不能够进行拓扑排序
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int indegree[1005],queue[1005],head[1005]; struct Edge { int to; int next; } edge[1005]; int main() { int n,m,i,j,k,iq,a,b; while(scanf("%d %d",&n,&m)!=EOF&&n&&m) { memset(head,-1,sizeof(head)); memset(indegree,0,sizeof(indegree)); for(i=1;i<=m;i++) { scanf("%d %d",&a,&b); edge[i].to=b; edge[i].next=head[a]; head[a]=i; indegree[b]++; } iq=0; for(i=0;i<n;i++) { if(indegree[i]==0) { queue[iq++]=i; } } for(i=0;i<iq;i++) { for(k=head[queue[i]];k!=-1;k=edge[k].next) { indegree[edge[k].to]--; if(indegree[edge[k].to]==0) { queue[iq++]=edge[k].to; } } } if(iq==n) printf("YES\n"); else printf("NO\n"); } }
时间: 2024-10-08 11:18:25