题目链接
问题分析:
题意:
rule1:胜负关系具有传递性
rule2:胜负关系形成闭环时,则闭环内的都不可能是冠军
所以大胆猜测,只要输过一次的人就不可能是冠军,统计最后没有输过的人数,若为1,则就是冠军,否则不能产生冠军!可以AC。
程序说明:
使用map<string, bool>
边输入边记录胜负属性,最后再用迭代器扫描一遍即可。
复杂度:
只是整体扫描了两遍,因此为O(n)
AC程序:
/**************************
//@Author: 3stone
//@ACM: HDU-2094 产生冠军
//@Time: 18/6/10
//@IDE: VSCode2018
***************************/
#include<cstdio>
#include<string>
#include<iostream>
#include<map>
using namespace std;
int main() {
int n, count;
map<string, bool> player;
string winner, loser;
while(cin >> n) {
if (n == 0)
break;
player.clear();
count = 0;
for (int i = 0; i < n; i++) {
cin >> winner >> loser;
if(player.find(winner) == player.end()) //若胜者是第一次出现
player[winner] = true;
player[loser] = false;
}
map<string, bool>::iterator it;
for(it = player.begin(); it != player.end(); it++) {
if (it->second)
count++;
}
if(count == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}//while
system("pause");
return 0;
}
程序参考:
海岛Blog 的解法思路与我一致,不过他用set
容器实现两个集合,然后size
作差显得更加清晰明了。