习题5-4 UVa10763-Foreign Exchange(map)

这道题很自然地会想到用map来解决,将学生的意愿a,b组成的对作为Key,统计相同的对出现的次数作为Value,最后判断每个映射的Value是否全为0即可。
这道题让我迷惑的地方在于,我想如果学生人数n为奇数的话匹配一定不成功,但是只要加入这个判定就会报WA…晕了
我还尝试过将学生的意愿a,b分别作为Key和Value,但是会报TLE,怀疑是数据变多以后循环时间过长的原因。

题目链接:UVa 10763

AC代码:

#include <iostream>
#include <map>
using namespace std;

map<pair<int, int>,int> num;

int main() {
	int n, a, b;
	while (cin >> n && n) {
		bool flag = false;
		num.erase(num.begin(), num.end());
		while(n--){
			cin >> a >> b;
			a < b ? num[make_pair(a, b)]++:num[make_pair(b, a)]--;  //都按照前小后大成对,有重复的话Value归零
		}
		for(map<pair<int,int>,int>::iterator iter=num.begin();iter!=num.end();iter++)
			if (iter->second) {
				cout << "NO" << endl;
				flag = true;
				break;
			}
		if (!flag)
			cout << "YES" << endl;
	}
	return 0;
}

TLE代码:(??)

#include <iostream>
#include <map>
using namespace std;

const int maxn = 500005;
multimap<int, int> num;

int main() {
	int n, a, b;
	while (cin >> n && n) {
		int cnt = 0, half = n / 2;
		while (n--) {
			cin >> a >> b;
			if (num.count(b)) {
				for (map<int, int>::iterator iter = num.find(b); iter != num.end(); iter++)
					if (iter->second == a) {
						cnt++;
						num.erase(iter);
						break;
					}
			}
			else
				num.insert(make_pair(a, b));
		}
		if (cnt == half)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值