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≤109), 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≤104). Then t test cases follow.
The first line of each test case contains a single integer n (1≤n≤2⋅105).
The second row of each test case contains n+2 integers b1,b2,…,bn+2 (1≤bi≤109).
It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.
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.
Example
input
4
3
2 3 7 12 2
4
9 1 7 1 6 5
5
18 2 2 3 2 9 2
3
2 6 9 2 1
output
2 3 7
-1
2 2 2 3 9
1 2 6
题意
本题的题意为给你一个数n和长度为n+2的数组,要求找出里面的长度为n的子数组。
要求这个子数组的总和等于剩下两个元素中的一个然后输出这个数组即可。
题解
因为是求和问题,所以我先排序找到最大和第二大的数。
1.当第二大 的数满足时,那么情况就只有一种,第二大的数就是前面所有数的和,那么输出前面所有的数就好了。
2.当第二大的数不满足时,那么结果就只能是和为最大的数,否则就找不到。对于结果是最大的数时,我们可以这样考虑,前面所有的数相加,如果小于等于最大数的话,那么一定找不到就直接返回-1,当它大于最大的数的话,那么前面数组减去其中一个数等于最大的数满足条件,否则就不满足返回-1,那我们是不是用这个和减去最大的数,这个差如果等于数组中的一个数就满足条件,输出除了这个数和最大的数的其他数,如果没有找到就返回-1.
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<memory>
#include<iomanip>
using namespace std;
#define ll long long
ll b[200005];
ll sum = 0;
int av;
int main() {
int t;
cin >> t;
int a;
while (t--) {
sum = 0;
cin >> a;
for (int i = 0; i < a + 2; i++) {
cin >> b[i];
}
sort(b, b + a + 2);//排序
for (int i = 0; i < a; i++) {
sum += b[i];
}
if (sum == b[a]) {
for (int i = 0; i < a; i++) {
cout << b[i];
if (i < a - 1)cout << " ";
}
cout << endl;
}
else {
sum = sum + b[a];
if (sum <= b[a + 1]) {
cout << "-1" << endl;
}
else {
ll s = sum - b[a + 1];
int l = 0;
int r = a;
while (l < r) {
av = l + (r - l) / 2;
if (b[av]<s) {
l = av + 1;
}
else {
r = av;
}
}
if (b[l] != s)cout << "-1" << endl;
else {
for (int i = 0; i < a+1; i++) {
if (i != l) {
cout << b[i];
if (i < a)cout << " ";
}
}
cout << endl;
}
}
}
}
return 0;
}