HDU2094 发生冠军 【STL】

HDU2094 产生冠军 【STL】

产生冠军

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8523    Accepted Submission(s): 4009


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


 

Input
输入含有一些选手群,每群选手都以一个整数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
 


STL版本 93ms:统计总人数和输掉的人数,若总-输==1则Yes,否则No。但是有个bug,比如A B, B C, D E, E F, F D。。

#include <iostream>
#include <set>
#include <string>
using namespace std;

int main()
{
	int n, count;
	string a, b;
	set<string> st, total;
	while(scanf("%d", &n), n){
		st.clear(); total.clear();
		count = 0;
		while(n--){
			cin >> a >> b;
			total.insert(a);
			total.insert(b);
			if(!st.count(b)){
				++count; st.insert(b);
			}
		}
		if(total.size() - st.size() == 1) cout << "Yes\n";
		else cout << "No\n";
	}
	return 0;
}


拓扑排序版本 15ms:只需要保证入度为0的点只有一个即可,无上述bug。

#include <stdio.h>
#include <string.h>

char str[2002][22];
int inDegree[2002], id;

int find(char str1[])
{
	for(int i = 0; i < id; ++i)
		if(!strcmp(str1, str[i])) return i;
	return -1;
}

void insert(char str1[])
{
	if(find(str1) != -1) return;
	strcpy(str[id++], str1);
}

int main()
{
	int n, i, count;
	char str1[22], str2[22];
	while(scanf("%d", &n), n){
		memset(inDegree, 0, sizeof(inDegree));
		id = count = 0;
		while(n--){
			scanf("%s%s", str1, str2);
			insert(str1); insert(str2);
			++inDegree[find(str2)];
		}
		for(i = 0; i < id; ++i)
			if(!inDegree[i]) ++count;
		if(count == 1) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}