← 所有笔记

codeforces.1512D - Corrupted Array

链接:https://codeforces.com/problemset/problem/1512/DCorrupted ArrayYou are given a number n and an array b1,b2,…,bn+2, obtained according to the follow

链接:https://codeforces.com/problemset/problem/1512/D

Corrupted Array

You are given a number n and an array b1,b2,…,bn+2, obtained according to the following algorithm:

some array a1,a2,…,an was guessed;
array a was written to array b, i.e. bi=ai (1≤i≤n);
The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. bn+1=a1+a2+…+an;
The (n+2)-th element of the array b was written some number x (1≤x≤1e9), i.e. bn+2=x; The
array b was shuffled.
For example, the array b=[2,3,7,12,2] it could be obtained in the following ways:

a=[2,2,3] and x=12;
a=[3,2,7] and x=2.
For the given array b, find any array a that could have been guessed initially.

Input
The first line contains a single integer t (1≤t≤1e4). Then t test cases follow.
The first line of each test case contains a single integer n (1≤n≤2e5).
The second row of each test case contains n+2 integers b1,b2,…,bn+2 (1≤bi≤1e9).
It is guaranteed that the sum of n over all test cases does not exceed 2e5

Output
For each test case, output:“-1”, if the array b could not be obtained from any array a;
n integers a1,a2,…,an, otherwise.If there are several arrays of a, you can output any.

AC代码

#include<bits/stdc++.h>
const int maxn = 2e5 + 10;
int a[maxn];
#define ll long long 
ll sum = 0;
using namespace std;
int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		bool flag = false;
		sum = 0;
		int n;
		scanf("%d", &n);
		for (int i = 1; i <= n + 2; i++)
		{
			scanf("%d", &a[i]);
		}
		sort(a + 1, a + 3 + n);
		for (int i = 1; i <= n; i++)
		{
			sum += a[i];
		}
		if (sum > a[n + 2])
		{
			printf("-1\n");
			continue;
		}
		else if (sum == a[n + 1]||sum==a[n+2])
		{
			for (int i = 1; i <= n; i++)
			{
				printf("%d ", a[i]);
			}
			printf("\n");
			continue;
		}
		else
		{
			sum += a[n + 1];
			for (int i = 1; i <= n + 1; i++)
			{
				int temp = sum - a[i];
				if (temp == a[n + 2])
				{
					a[i] = 0;
					flag = true;
					break;
				}
			}
			if (flag)
			{
				for (int i = 1; i <= n + 1; i++)
				{
					if (a[i] != 0)
					{
						printf("%d ", a[i]);
					}
				}
				printf("\n");
			}
			else
				printf("-1\n");
		}
	}
	return 0;
}

好好反思自己为什么做不对啊!!zhx!!💢💢💢

✳

谢谢你读到这里。

更新于 2022-05-29

搜索笔记

搜索文章标题、标签和正文。

↑ ↓ 选择 · Enter 阅读Esc 关闭