Codeforces Round #849 (Div. 4)--E. Negatives and Positives

Given an array a consisting of nn elements, find the maximum possible sum the array can have after performing the following operation any number of times:

  • Choose 2 adjacent elements and flip both of their signs. In other words choose an index i such that 1≤i≤n−1 and assign ai=−ai and ai+1=−ai+1.

Input

The input consists of multiple test cases. The first line contains an integer t (1≤t≤1000) — the number of test cases. The descriptions of the test cases follow.

The first line of each test case contains an integer n (2≤n≤2⋅10^5) — the length of the array.

The following line contains n space-separated integers a1,a2,…,an (−10^9≤ai≤10^9).

It is guaranteed that the sum of nn over all test cases does not exceed 2⋅10^5.

Output

For each test case, output the maximum possible sum the array can have after performing the described operation any number of times.

输入:

5
3
-1 -1 -1
5
1 5 -5 0 2
3
1 2 3
6
-1 10 9 8 7 6
2
-1 -1

输出:

1
13
6
39
2

Note

For the first test case, by performing the operation on the first two elements, we can change the array from [−1,−1,−1] to [1,1,−1], and it can be proven this array obtains the maximum possible sum which is 1+1+(−1)=1.

For the second test case, by performing the operation on −5 and 0, we change the array from [1,5,−5,0,2] to [1,5,−(−5),−0,2]=[1,5,5,0,2], which has the maximum sum since all elements are non-negative. So, the answer is 1+5+5+0+2=13.

For the third test case, the array already contains only positive numbers, so performing operations is unnecessary. The answer is just the sum of the whole array, which is 1+2+3=6.

题意:给定长度n的数组,可以有若干次操作使得ai和ai+1的数字正负变化,问最终数组和最大是多大。

解析:知道一个得出的结论即可,就是记录负数的个数,如果是偶数,那么都可以转正,如果是奇数,那么剩下一个负数,相当于可以转移负号给别的数,那么肯定是转移给绝对值最小的那个数,如果那个数是正数,需要改变符号。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+5;
ll a[N];
void solve()
{
	int n,m=0;
	ll minn=1e9;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%lld",&a[i]);
		if(a[i]<0) m++;//记录负数的个数
		minn=min(abs(a[i]),minn);//保存绝对值最小的数
	}
	if(m%2==0)//偶数
	{
		ll sum=0;
		for(int i=1;i<=n;i++)
		{
			sum+=abs(a[i]);
		}
		printf("%lld\n",sum);
		return;
	}else//奇数
	{
		ll sum=0,cnt=1;
		for(int i=1;i<=n;i++)
		{
			if(abs(a[i])==minn&&cnt==1)//就转移一次
			{
				if(a[i]>0) a[i]*=-1;//转给正数
				sum+=a[i],cnt=0;//是他自己
			}
			else sum+=abs(a[i]);
		}
		printf("%lld\n",sum);
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--) solve();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值