习题5_4 交换学生(Foreign Exchange, UVa 10763)
题目描述:
有n(1 <= n <= 500000)个学生想交换到其他学校学习。为了简单起见,规定每个想从A学校换到B学校的学生必须找一个想从B换到A的“搭档”。如果每个人都能找到搭档(一个人不能当多个人的搭档),学校就会同意他们交换。每个学生用两个整数A、B表示,你的任务是判断交换是否可以进行
#include<cstdio>
#include<iostream>
#include<vector>
#include<map>
using namespace std;
typedef pair<int, int> P;
vector<P> stu;
map<P, int> m;
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n;
while(cin >> n) {
stu.clear();
m.clear();
bool flag = true;
if(n == 0) break;
while(n--) {
int i, j;
cin >> i >> j;
P p = make_pair(i, j);
stu.push_back(p);
if(!m.count(p)) m[p] = 1;
else m[p]++;
if(m[p] == m[make_pair(j,i)]) {
m[p] = 0;
m[make_pair(j, i)] = 0;
}
}
for(int i = 0; i < stu.size(); i++) {
if(m[stu[i]] == 1) flag = false;
}
if(flag) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}