九度oj 题目1450:产生冠军

题目描述:

有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比赛。
球赛的规则如下:
如果A打败了B,B又打败了C,而A与C之间没有进行过比赛,那么就认定,A一定能打败C。
如果A打败了B,B又打败了C,而且,C又打败了A,那么A、B、C三者都不可能成为冠军。
根据这个规则,无需循环较量,或许就能确定冠军。你的任务就是面对一群比赛选手,在经过了若干场撕杀之后,确定是否已经实际上产生了冠军。

输入:

输入含有一些选手群,每群选手都以一个整数n(n<1000)开头,后跟n对选手的比赛结果,比赛结果以一对选手名字(中间隔一空格)表示,前者战胜后者。如果n为0,则表示输入结束。

输出:

对于每个选手群,若你判断出产生了冠军,则在一行中输出“Yes”,否则在一行中输出“No”。

样例输入:
3
Alice Bob
Smith John
Alice Smith
5
a c
c d
d e
b e
a d
0
样例输出:
Yes
No
这道题开始有些不知所措,不知道从哪里下手。
参考别人代码后明白,它其实是判断是不是只有一个根,对于输入 A B ,只需使 isRoot[B] = 0,最后看还有多少isRoot为1的即可
 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <string>
 5 #include <algorithm>
 6 #define MAX 1002
 7 #define NAMEM 102
 8 
 9 char name[MAX][NAMEM];
10 int isRoot[MAX];
11 char buf1[NAMEM];
12 char buf2[NAMEM];
13 
14 int main(int argc, char const *argv[])
15 {
16     //freopen("input.txt","r",stdin);
17     int n;
18     scanf("%d",&n);
19     while(n != 0) {
20         for(int i = 0; i < n; i++) {
21             isRoot[i] = 1;
22         }
23 
24         int peopleCnt = 0;
25         for(int i = 0; i < n; i++) {
26             scanf("%s %s",buf1,buf2);
27             bool find1 = false, find2 = false;
28             for(int j = 0; j < peopleCnt; j++) {
29                 if(strcmp(buf1,name[j]) == 0) {
30                     find1 = true;
31                 }
32                 if(strcmp(buf2,name[j]) == 0) {
33                     isRoot[j] = 0;
34                     find2 = true;
35                 }
36             }
37             if(!find1) {
38                 strcpy(name[peopleCnt],buf1);
39                 name[peopleCnt][strlen(buf1)] = '';
40                 peopleCnt++;
41             }
42             if(!find2) {
43                 strcpy(name[peopleCnt],buf2);
44                 name[peopleCnt][strlen(buf2)] = '';
45                 isRoot[peopleCnt] = 0;
46                 peopleCnt++;
47             }
48         }
49         int res = 0;
50         for(int i = 0; i < peopleCnt; i++) {
51             res += isRoot[i];
52         }
53         if(res == 1) {
54             printf("%s
","Yes");
55         }
56         else {
57             printf("%s
", "No");
58         }
59         scanf("%d",&n);
60     }
61     return 0;
62 }
原文地址:https://www.cnblogs.com/jasonJie/p/5710645.html