Legal or Not
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2602 Accepted Submission(s): 1158
We all know a master can have many prentices and a prentice may have a lot of masters too, it's legal. Nevertheless,some cows are not so honest, they hold illegal relationship. Take HH and 3xian for instant, HH is 3xian's master and, at the same time, 3xian is HH's master,which is quite illegal! To avoid this,please help us to judge whether their relationship is legal or not.
Please note that the "master and prentice" relation is transitive. It means that if A is B's master ans B is C's master, then A is C's master.
TO MAKE IT SIMPLE, we give every one a number (0, 1, 2,..., N-1). We use their numbers instead of their names.
If it is legal, output "YES", otherwise "NO".
代碼:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxx=105;
//degree[] 每個結點的入度
//f[] 每個結點所在的層
int degree[maxx];
int f[maxx];
int map[maxx][maxx];
int top;
int n,m;
bool Toplogical_sort()
{
int i,j;
bool p=true;
top=0;
int tmp=0;
while(p)
{
p=false;
top++;
tmp=-1;
for(i=0; i<=n-1; i++)
if(degree[i]==0)
{
p=true;
f[i]=top;
tmp=i;
break;
}
if(tmp==-1)
continue;
for(j=0; j<n; j++)
{
if(map[tmp][j])
degree[j]--;
degree[tmp]=-1;
}
}
top--;
if(top<n)
return false;
return true;
}
int main()
{
while(scanf("%d%d",&n,&m))
{
if(n==0)
break;
memset(map,0,sizeof(map));
memset(f,0,sizeof(f));
memset(degree,0,sizeof(degree));
int a,b;
for(int i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
if(!map[a][b])
{
map[a][b]=1;
degree[b]++;
}
}
if(Toplogical_sort())
{
printf("YES\n");
}
else printf("NO\n");
}
return 0;
}