产生冠军
题目描述
有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比赛。
球赛的规则如下:
如果A打败了B,B又打败了C,而A与C之间没有进行过比赛,那么就认定,A一定能打败C。
如果A打败了B,B又打败了C,而且,C又打败了A,那么A、B、C三者都不可能成为冠军。
根据这个规则,无需循环较量,或许就能确定冠军。你的任务就是面对一群比赛选手,在经过了若干场撕杀之后,确定是否已经实际上产生了冠军。
Iutput
输入含有一些选手群,每群选手都以一个整数n(n<1000)开头,后跟n对选手的比赛结果,比赛结果以一对选手名字(中间隔一空格)表示,前者战胜后者。如果n为0,则表示输入结束。
Output
对于每个选手群,若你判断出产生了冠军,则在一行中输出“Yes”,否则在一行中输出“No”。
Sample Input
3
Alice Bob
Smith John
Alice Smith
5
a c
c d
d e
b e
a d
0
Sample Output
Yes
No
思路:
先用map存储各位选手们的名字,统计出现在代表输了比赛的右边的选手姓名的次数;最后有人出现在失败那边的次数为0,且这样的人只有一个,那么他就是冠军;
拓展解法:据说可以用拓扑排序,并查集来做
代码
#include <map>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 1010;
int n;
char str1[110], str2[110];
int in[N];
int main()
{
while (~scanf("%d", &n), n)
{
map<string, int>qu;
memset (in, 0, sizeof(in));
qu.clear();
int cnt = 0;
for (int i = 1; i <= n; ++i)
{
scanf("%s%s", str1, str2);
if (qu[str1] == 0)
{
qu[str1] = ++cnt;
}
if (qu[str2] == 0)
{
qu[str2] = ++cnt;
}
in[qu[str2]]++;
}
int ans = 0;
for (int i = 1; i <= cnt; ++i)
{
if (in[i] == 0)
{
ans++;
}
}
if (ans >= 2 || ans == 0)
{
printf("No\n");
continue;
}
printf("Yes\n");
}
return 0;
}