CodeForces - 1474C Array Destruction(set+思维)

题目链接:点击这里

题目大意:
给定一个长度为 2 n 2n 2n 的序列 a 1 , a 2 , . . . , a 2 n a_1,a_2,...,a_{2n} a1,a2,...,a2n ,最开始,选定一个数 x x x ,接下来执行若干步操作:

  1. 在序列中选出 a i , a j a_i,a_j ai,aj 满足 a i + a j = x a_i+a_j=x ai+aj=x
  2. 将两者从数组中删除,并更新 x = m a x ( a i , a j ) x=max(a_i,a_j) x=max(ai,aj)

问是否能删除整个序列,如果可以,打印 Y E S YES YES 并输出 x x x 和一组可行的方案,如果不能打印 N O NO NO

题目分析:
当我们选定 x x x 后,每次操作一定会消除剩余元素的最大值,否则最大值将无法通过后续操作删除
因此 x x x 一定含有 m a x a i max_{a_i} maxai 故我们只需枚举 x x x 的另一半,然后维护一个 m u l t i s e t multiset multiset 来检查这个 x x x 是否合法
,每次执行完操作就把数字从 m u l t i s e t multiset multiset 中剔除
如果存在合法方案,则每次操作 x − m a x a i x-max_{a_i} xmaxai 都能在 m u l t i s e t multiset multiset 中找到对应的元素
时间复杂度为 O ( n 2 l o g n ) O(n^2logn) O(n2logn)

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e5+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
int n,nn,cnt,a[maxn];
bool vis[maxn];
multiset<int>s,tmp;
pair<int,int>ans[maxn];
bool solve(int pos)
{
	int pre = a[nn];
	multiset<int>::iterator iter = tmp.find(a[nn]);
	tmp.erase(iter);
	iter = tmp.find(a[pos]);
	tmp.erase(iter);
	ans[1].first = a[nn],ans[1].second = a[pos];
	cnt = 1;
	for(int i = nn-1;i && cnt<n;i--)
	{
		iter = tmp.find(a[i]);
		if(iter == tmp.end()) continue;
		else tmp.erase(iter);
		iter = tmp.find(pre-a[i]);
		if(iter == tmp.end() && cnt != n) 
			return false;
		else tmp.erase(iter);
		ans[++cnt].first = a[i];ans[cnt].second = *iter;
		pre = a[i];
	}
	return cnt==n;
}
int main()
{
	int t = read();
	while(t--)
	{
		n = read(); nn = n*2;
		s.clear();
		for(int i = 1;i <= nn;i++)
			s.insert(a[i] = read());
		sort(a+1,a+nn+1);
		bool flag = false;
		for(int i = nn-1;i&&!flag;i--)
		{
			tmp = s;
			flag = solve(i);
		}
		if(flag)
		{
			puts("YES");
			printf("%d\n",ans[1].first+ans[1].second);
			for(int i = 1;i <= cnt;i++)
				printf("%d %d\n",ans[i].first,ans[i].second);
		}
		else puts("NO");
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值