习题5-4 交换学生(Foreign Exchange,UVa 10763)

原题链接:https://vjudge.net/problem/UVA-10763
分类:
备注:水题
前言:再次看到数据超水的题,直接排序都能过就很离谱了。

错误AC(排序)代码如下:

#include
#include
#include
using namespace std;
int main(void)
{
	int T;
	while (~scanf("%d", &T) && T)
	{
		vector<int>A, B;
		int a, b, flag = 1;
		for (int i = 0; i < T; i++)
		{
			scanf("%d%d", &a, &b);
			A.push_back(a); B.push_back(b);
		}
		sort(A.begin(), A.end());
		sort(B.begin(), B.end());
		for (int i = 0; i < A.size(); i++)
			if (A[i] != B[i])
			{
				flag = 0;
				break;
			}
		if (flag)printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}

正确AC代码如下:

#include
#include
#include
using namespace std;
typedef pair<int, int>PII;
int main(void)
{
	int n;
	while (~scanf("%d", &n) && n)
	{
		int A, B;
		map<PII, int>want;
		vector<PII>cache;
		for (int i = 0; i < n; i++)
		{
			scanf("%d%d", &A, &B);
			if (!want.count(PII(A, B)))
			{
				want[PII(A, B)] = 0;
				cache.push_back(PII(A, B));
			}
			want[PII(A, B)]++;
		}
		int flag = 1;
		for (int i = 0; i < cache.size(); i++)
		{
			int A = cache[i].first;
			int B = cache[i].second;
			if (want[PII(A, B)] != want[PII(B, A)])
			{
				flag = 0;
				break;
			}
		}
		if (flag)printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}

你可能感兴趣的:(《算法竞赛入门经典(第2版)》)