E - 简单的dp
Given an array �a consisting of �n elements, find the maximum possible sum the array can have after performing the following operation any number of times:
Choose 22 adjacent elements and flip both of their signs. In other words choose an index �i such that 1≤�≤�−11≤i≤n−1 and assign ��=−��ai=−ai and ��+1=−��+1ai+1=−ai+1.
Input
The input consists of multiple test cases. The first line contains an integer �t (1≤�≤10001≤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≤�≤2⋅1052≤n≤2⋅105) — the length of the array.
The following line contains �n space-separated integers �1,�2,…,��a1,a2,…,an (−109≤��≤109−109≤ai≤109).
It is guaranteed that the sum of �n over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, output the maximum possible sum the array can have after performing the described operation any number of times.
Sample 1
Inputcopy | Outputcopy |
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][−1,−1,−1] to [1,1,−1][1,1,−1], and it can be proven this array obtains the maximum possible sum which is 1+1+(−1)=11+1+(−1)=1.
For the second test case, by performing the operation on −5−5 and 00, we change the array from [1,5,−5,0,2][1,5,−5,0,2] to [1,5,−(−5),−0,2]=[1,5,5,0,2][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=131+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=61+2+3=6.
思路
没搞懂怎么用排序就可以解决问题,所以学习了一下别人的解法。把负数记录再数组a中,判断负数的数量是否是偶数,如果是就直接abs相加,不是那个绝对值最小的数不变进行加和。
#include<stdio.h>
#define MAX 200010
long long a[MAX];
int min(int x,int y)
{
return (x<y)?x:y;
}
int abs(int x)
{
if(x<0)
return -x;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m=0;
long long k=1e9;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
if(a[i]<0)
m++;
k=min(abs(a[i]),k);
}
if(m%2==0)
{
long long sum=0;
for(int i=1;i<=n;i++)
sum=sum+abs(a[i]);
printf("%lld\n",sum);
continue;
}
else
{
long long sum=0,count=1;
for(int i=1;i<=n;i++)
{
if(abs(a[i])==k&&count==1)
{
if(a[i]>0) a[i]*=-1;
sum=sum+a[i],count=0;
}
else
sum=sum+abs(a[i]);
}
printf("%lld\n",sum);
}
}
return 0;
}