Problem Description ACM-DIY is a large QQ group where many excellent acmers get together. It is so harmonious that just like a big family. Every day,many "holy cows" like HH, hh, AC, ZT, lcc, BF, Qinz and so on chat on-line to exchange their ideas. When someone has questions, many warm-hearted cows like Lost will come to help. Then the one being helped will call Lost "master", and Lost will have a nice "prentice". By and by, there are many pairs of "master and prentice". But then problem occurs: there are too many masters and too many prentices, how can we know whether it is legal or not?
Input The input consists of several test cases. For each case, the first line contains two integers, N (members to be tested) and M (relationships to be tested)(2 <= N, M <= 100). Then M lines follow, each contains a pair of (x, y) which means x is y's master and y is x's prentice. The input is terminated by N = 0.
Output For each test case, print in one line the judgement of the messy relationship. Sample Input 3 2 0 1 1 2 2 2 0 1 1 0 0 0
Sample Output YES NO |
拓扑排序,必须考虑重边的情况
#include<bits/stdc++.h>
using namespace std;
int n,m,g[110][110],in[110],k;
queue< int > q;
void topo()
{
int ans = 0;
for(int i = 0;i < n;i ++)
{
int j = 0;
while(in[j])
j++;
in[j] = -1;
for(int k = 0;k < n;k ++)
{
if(g[j][k])
{
in[k] --;
ans ++;
}
}
}
if(ans == k)
printf("YES\n");
else
printf("NO\n");
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n == 0&&m == 0)
break;
k = m;
memset(in,0,sizeof(in));
memset(g,0,sizeof(g));
int a,b;
for(int i = 0;i < m;i ++)
{
scanf("%d%d",&a,&b);
if(!g[a][b])
{
g[a][b] = 1;
in[b] ++;
}
else
k--;//重边的情况
}
topo();
}
return 0;
}