Legal or Not
作者:互联网
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?
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.
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.
TO MAKE IT SIMPLE, we give every one a number (0, 1, 2,…, N-1). We use their numbers instead of their names.
Output
For each test case, print in one line the judgement of the messy relationship.
If it is legal, output “YES”, otherwise “NO”.
Sample Input
3 2
0 1
1 2
2 2
0 1
1 0
0 0
Sample Output
YES
NO
题意:
输入数据n,m,表示有n个人接下来m行,每行输入x,y表示x是y的师父;
如果A是B的师父B是C的师父,则A是C的师父
如果A是B的师父,B又是A的师父则不合法输出No,如果合法输出YES
思路:
本题的关键是怎么判断成环,通过拓扑排序的方法把输入的数据排序,由拓扑排序可知,每次都能找到一个数放到该序列里,如果有一步找不到,就说明成环了,输出NO,如果结束时还没出现上面情况,输出YES。
//#include<bits/stdc++.h>//不建议依赖万能头文件
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int INF=0x3f3f3f3f;
int Map[510][510];// 存放数据
int in[510],n,m;//数组in储存度
void to()
{
int i,j,t=0,k=INF;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
if(in[j]==0)//查找前驱为零的点 有则记录 无则准备结束
{
k=j;
break;
}
else
k=INF;
if(k==INF)//判断是否成环
{
cout<<"NO"<<endl;
return;
}
in[k]=-1; //将该点删除
for(int v=1; v<=n; v++)//删除与该点有联系的弧
{ //即与该点相连的点的度均减一
if(Map[k][v])
in[v]--;
}
}
cout<<"YES"<<endl;
}
int main()
{
while(cin>>n>>m)//多组数据 切记
{
if(n==0&&m==0)
break;
memset(Map,0,sizeof(Map));
memset(in,0,sizeof(in));
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
a+=1;b+=1; //数据含0 故+1 与数组下标对应
if(Map[a][b]==0)//构建联系且储存度
{
Map[a][b]=1;
in[b]++;
}
}
to();
}
return 0;
}
非原创!
标签:Map,int,many,Legal,master,YES,include 来源: https://blog.csdn.net/weixin_43778091/article/details/96486701