Legal or Not
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11846 Accepted Submission(s): 5570
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?
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
题意:群里有许多人,为了方便,人用0-N-1编号,如果1帮助了2,那么说1是2的师父,2是1的徒弟。一个人可以有多个徒弟,同理一个人可以有多个师父,师徒关系具有传递性。这其中可能有人说谎了,如1说1是2的师父,2说2是1的师父(两个人都是对方的师父),写个程序判断给定数据是否有人说谎。
可以将输入抽象为有向图,由师父指向徒弟的一条边,师徒关系的传递性在有向图中体现为一条路径上前面的顶点是后面的顶点的师父,这样的话,如果出现了有向环就表示有人说谎(互为对方的师父)。判断有向图中是否存在环可以直接用拓扑排序做,如果拓扑排序后顶点个数小于图中的顶点数,则表示图中有环。
#include "iostream"
#include "vector"
#include "queue"
using namespace std;
int N, M;
int tuopo(vector<vector<int> > & map, vector<int> & degree){
queue<int> q;
int result = 0;
for (int i = 0; i < N;i++){
if(degree[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int point = q.front();
q.pop();
result++;
for (int i = 0; i < N;i++){
if(map[point][i] == 1){
if(--degree[i] == 0){//删除边
q.push(i);
}
}
}
}
return result;
}
int main(){
while(cin>>N>>M && N){
vector<int> degree(N, 0);
vector<vector<int> > map(N, vector<int>(N, 0));//邻接矩阵存储
for (int i = 0; i < M;i++){
int x, y;
cin >> x >> y;
if(map[x][y] == 0){
map[x][y] = 1;
degree[y]++;
}
}
int result = tuopo(map, degree);
if(result==N)
cout << "YES" << endl;
else
{
cout << "NO" << endl;
}
}
//system("pause");
return 0;
}