题目:
n个学生想换学校,如果每位学生都有和他唯一直接互补的学生(比如从A到B有k个学生,则从B到A必须也为k个),认为可以,反之不可
注意:我们认为 间接匹配是不可以的(即对于每个学生能且只能匹配一个直接互补的学生)
思路:
为了好理解,举个简单的例子 (1 2)(3 4) 需要找到 (2 1) (4 3)
可以发现:
二元组各元排序后前: (1 3 2 4)(2 4 1 3)看似没有规律
二元组各元排序后后: (1 2 3 4)(1 2 3 4)是完全相同的
所以此题排序可解
以下代码是学习STL不久所写,虽然比较水但是好理解:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> a, b;
int main()
{
int n;
int p1, p2;
while (cin >> n && n)
{
a.clear();
b.clear();
while (n--)
{
cin >> p1 >> p2;
a.push_back(p1);
b.push_back(p2);
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (a == b)
cout << "YES" << endl;
else
cout << "NO"<<endl;
}
return 0;
}
然后是精简版:
#include <cstdio>
#include <set>
using namespace std;
int main() {
int n, p, k;
while (scanf("%d",&n) == 1 && n) {
multiset<int> a, b;
while (n--) {
scanf("%d%d", &p, &k);
a.insert(p);
b.insert(k);
}
printf("%s\n", a == b ? "YES" : "NO");
}
return 0;
}
备注:其实当n为奇数时,一定是“NO”
但是还需要读入数据,所以就不单独处理了