原题链接:
题目描述:
You are given an array aa consisting of nn integers. You want to distribute these nn integers into two groups s1s1 and s2s2 (groups can be empty) so that the following conditions are satisfied:
- For each ii (1≤i≤n)(1≤i≤n), aiai goes into exactly one group.
- The value |sum(s1)|−|sum(s2)||sum(s1)|−|sum(s2)| is the maximum possible among all such ways to distribute the integers.
Here sum(s1)sum(s1) denotes the sum of the numbers in the group s1s1, and sum(s2)sum(s2) denotes the sum of the numbers in the group s2s2.
Determine the maximum possible value of |sum(s1)|−|sum(s2)||sum(s1)|−|sum(s2)|.
Input
The input consists of multiple test cases. The first line contains a single integer tt (1≤t≤2⋅104)(1≤t≤2⋅104) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤105)(1≤n≤105) — the length of the array aa.
The second line of each test case contains nn integers a1,a2…ana1,a2…an (−109≤ai≤109)(−109≤ai≤109) — elements of the array aa.
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, output a single integer — the maximum possible value of |sum(s1)|−|sum(s2)||sum(s1)|−|sum(s2)|.
题目大意:
给定一个长度为n的整数数组,让你分成s1、s2li,问如何分使得两组的和的绝对值差最大。可以允许一组为空。
解题思路:
正数负数分开放即可。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e5 + 10;
const int INF = 0x3fffffff;
int n;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
while(t--)
{
int a = 0, b = 0;
cin >> n;
for(int i = 1, x; i <= n; i++) {
cin >> x;
if(x < 0)
a += -x;
else
b += x;
}
cout << llabs(a - b) << '\n';
}
return 0;
}