You are given an array a of n integers, and an integer k. You have to make k negation operations such that at each operation you need to choose an element ai from the array and replace it with −ai.
Your task is to find the optimal way to make the k negation operations such that at the end the sum of the array a is as maximal as possible. Can you?
Input
The first line contains an integer T (1≤T≤100) specifying the number of test cases.
The first line of each test case contains two integers n and k (1≤n≤104, 0≤k≤104), in which n is the size of the array, and k is the number of negation operations to be made.
Then a line follows contains n integers a1,⋯,an (−100≤ai≤100), giving the array a.
Output
For each test case, print a single line containing the maximum sum of array a after making the required number of negation operations.
Example
Input
3
3 1
4 6 2
4 2
-1 0 2 1
5 2
1 7 -4 2 -3
Output
8
4
17
Note
In the first test case, the optimal way is to make the negation operation on a3. After this, the array will be = [4,6,−2], and its sum is 8.
思路:
统计数组中负数的个数,为num,如果k>num,则说明所有的负数都会被改成正数,剩下的k-num次都只取反最小的正数就好了;否则的话,那就先把数组排序一下,只把前k个取反就好啦~
#include<bits/stdc++.h>
using namespace std;
int a[10001];
int main()
{
std::ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
int n,k;
cin>>n>>k;
int num=0;//负数的个数
for(int i=0; i<n; i++)
{
cin>>a[i];
if(a[i]<0)
{
num++;
}
}
if(num<=k)
{
int minn=99999999;
int x=-1;
for(int i=0; i<n; i++)
{
if(a[i]<0)
{
a[i]=-a[i];
}
if(a[i]<minn)
{
minn=a[i];
x=i;
}
}
if((k-num)%2!=0)
{
a[x]=-a[x];
}
}
else
{
sort(a,a+n);
for(int i=0; i<k; i++)
a[i]=-a[i];
}
long long int sum=0;
for(int i=0; i<n; i++)
sum+=a[i];
cout<<sum<<endl;
}
return 0;
}