跳到正文

题解

题解 CF468B 【Two Sets】

pufanyi约 3 分钟
原文
文章信息与版本

文章信息

发布
2018年9月8日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
19
题目
CF468B

版本

  1. v1当前

感觉网上全是并查集的题解。

没有贪心?

感觉贪心比并查集好想啊……

首先我们想到的肯定是开个set大力匹配,然而发现对于一个xx可能a−xa-x和b−xb-x都在序列中,于是我们就陷入两难了。

如何解决这个问题呢?

现在我们假设a≥ba\ge b。

我们每次贪心地选出没有匹配过的数的最小值,设其为xx。

假设我们发现a−xa-x和b−xb-x都在序列中且都没有被匹配过。

我们会发现xx一定与a−xa - x匹配。

假设答案是xx与b−xb - x匹配,那也就是说a−xa - x不在AA集合里,所以其在BB集合里,则与之匹配的是b−(a−x)=x+(b−a)≤xb - (a - x) = x + (b - a)\le x,但由于xx是序列中的最小数,所以不存在b−(a−x)b - (a - x)。

代码也很简单:

C++
#include <cstdio>
#include <cstring>
#include <set>

using namespace std;

const int maxn = 100005;

int ans[maxn];

struct EE
{
	int x, id;

	inline bool operator < (const EE& other) const
	{
		return this->x < other.x;
	}
} aa[maxn];

set<EE> ss;

int main()
{
	int n, a, b;
	scanf("%d%d%d", &n, &a, &b);
	ss.clear();
	bool f = false;
	if(a < b)
	{
		swap(a, b);
		f = true;
	}
	for(int i = 1; i <= n; ++i)
	{
		EE aa;
		scanf("%d", &aa.x);
		aa.id = i;
		ss.insert(aa);
	}
	memset(ans, 0xff, sizeof(ans));
	while(!ss.empty())
	{
		set<EE>::iterator it = ss.begin();
		EE tx = *it;
		tx.x = a - it->x;
		set<EE>::iterator x = ss.lower_bound(tx);
		if(x != ss.end() && x->x + it->x == a)
		{
			ans[x->id] = ans[it->id] = 0;
			if(x->id != it->id)
			{
				ss.erase(x);
				ss.erase(it);
			}
			else
				ss.erase(x);
		}
		else
		{
			tx.x = b - it->x;
			x = ss.lower_bound(tx);
			if(x != ss.end() && x->x + it->x == b)
			{
				ans[x->id] = ans[it->id] = 1;
				if(x->id != it->id)
					ss.erase(it);
				ss.erase(x);
			}
			else
				return puts("NO"), 0;
		}
	}
	puts("YES");
	for(int i = 1; i <= n; ++i)
		printf("%d ", ans[i] ^ f);
	return 0;
}
原文
存档评论1 条抓取于