Codeforces Round #696 (Div. 2) C. Array Destruction

https://codeforces.com/contest/1474/problem/C
思路:通过思考可以发现取两个数为一组,其中的最大值为下一组的x,那么第1组就要有数组的最大的数a,第2组要包含数组第二大的数b,因为不这么做的化,比如取第三大的数c和另一个数d组成c+d = a,那么c就是下一个x,
而这个x比b小,同时x的值是越来越小的,那么就无法去掉b了。
因此,知道每一组都要取剩下的数组的最大的一个数之后,从第二组开始,由于x已经确定就是初始数组最大的数,同时第二组的一个数字可以确定,那么第二组的另一个数也可以确定,以此类推,第2组到第n组的数都可一确定了,唯一不确定的就是第一组数的另一个值。
于是我们可以通过遍历这个不确定的值,让剩下的数组成第二组、第三组、、第n组,看看能不能组出来,可以则输出yes,否则就输出no。
附上代码:

#include <iostream>
#include <algorithm>
#include <string.h>
#include <map>
#include <math.h>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn = 1e6+10;
const long long INF = 1e18;
 
int a[maxn];
int b[maxn];
int cmp(int a,int b){
	return a>b;
}
 
struct node{
	int a,b;
};
struct node c[maxn];
int index=1;
int cnt = 0;
int flag =0;
int n;
 
void dfs(int fmax , int now,int cnt){
	if(b[a[now]]>0){
		b[a[now]]--;
		if(b[fmax - a[now]]>0){
			c[index].a = a[now];
			c[index].b = fmax - a[now];
			b[fmax - a[now]]--;
			index ++;
			if(cnt ==n) {
				flag = 1;
				return ;
			}
			dfs(a[now] , now+1 , cnt+1);
			if(flag ==1) return ;
			b[fmax - a[now]]++;
			index--;
		}
		b[a[now]]++;
	}
	else if(now<n*2) dfs(fmax , now+1 , cnt);
}
 
int main() {
	
	int t;
	cin>>t;
	while(t--){
		
		index = 1;
		flag =0;
		cnt = 1;
		for(int i=0;i<=1e6;i++){
			b[i]=0;
		}
		cin>>n;
		for(int i=1;i<=2*n;i++) {
			
			cin>>a[i];
			b[a[i]]++;
		}	
		sort(a+1,a+n*2+1,cmp);
		b[a[1]]--;
		for(int i=2;i<=n*2;i++){
			b[a[i]]--;
			c[index].a = a[1];
			c[index].b = a[i];
			index++;
			dfs(a[1] , 2 , 2 );
			if(flag){
				break;
			}
			b[a[i]]++;
			index--;
		}
		if(n==1) {
			flag = 1;
			index = 2;
		}
		if(flag){
			cout<<"YES\n";
			cout<<c[1].a+c[1].b<<endl;
			for(int i=1;i<index;i++){
				cout<<c[i].a<<" "<<c[i].b<<endl;
			}
		}
		else cout<<"NO\n";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yin101_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值