产生冠军

题目网址:产生冠军

题目存在两个易错点,我也是改了很久才发现的,都在代码中注释出来了,第一处就是map忘记清空,第二个就是对于题目所给的案例二,考虑不够充分,案例二虽然满足拓扑排序,但是无法产生冠军,因为最开始入度为0的点有两个,那么这两个人是无法区分出冠军的!(a和d是无法判断谁是冠军的,但是如果按照常规的求解拓扑序列的算法来求,那么输出的肯定是yes,拓扑序列看得是是否是无环图)。修改的方法就是初始入度为0的点入栈,判断栈内元素的个数,如果大于1,那么就是输出no,剩下的不要判断了!

#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<string>
using namespace std;
vector<int> edge[1001];
queue<int> q;
map<string, int> m;//表示每一个人的名字和他的编号的对应
string str1, str2;//表示两组人的
int indegree[1001];
int main()
{
	int n;
	while (cin >> n&&n)
	{
		int cnt = 0;//表示参赛选手的人数
		for (int i = 0; i < 1001; i++)
		{//初始化,不可少
			edge[i].clear();
			indegree[i] = 0;
		}
		m.clear();//易错点,容易遗漏
		for (int i = 0; i < n; i++)
		{
			cin >> str1 >> str2;
			int a, b;//a和b分别是用来保存输入的两人的编号
			if (m.find(str1) == m.end())
			{//没有查找到,则插入m中
				m.insert(make_pair(str1, cnt));
				a = cnt;
				cnt++;
			}
			else
			{
				a = m.find(str1)->second;
			}
			if (m.find(str2) == m.end())
			{
				m.insert(make_pair(str2, cnt));
				b = cnt;
				cnt++;
			}
			else
			{
				b = m.find(str2)->second;
			}
			edge[a].push_back(b);
			indegree[b]++;
		}
		//cout << cnt << endl;
		/*map<string, int>::iterator it = m.begin();
		for (; it != m.end(); it++)
		{
			cout << it->first << ' ' << it->second << endl;
		}*/
		while (!q.empty())
			q.pop();
		for (int i = 0; i < cnt; i++)
		{
			if (indegree[i] == 0)
				q.push(i);
		}
		if (q.size() != 1)
		{//这个也是易错点,如果没有这个,第二个案例就是yes,必须只能有一个冠军
			cout << "No" << endl;
			continue;
		}
		int ans = 0;
		while (!q.empty())
		{
			int now = q.front();
			q.pop();
			ans++;
			for (int j = 0; j < edge[now].size(); j++)
			{
				indegree[edge[now][j]]--;
				if (indegree[edge[now][j]] == 0)
					q.push(edge[now][j]);
			}
		}
		if (ans == cnt)
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值