这道题很自然地会想到用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;
}