训练赛3_H_Roma and Changing Signs.md

Roma and Changing Signs

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Roma works in a company that sells TVs. Now he has to prepare a report for the last year.

Roma has got a list of the company’s incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.

The operation of changing a number’s sign is the operation of multiplying this number by -1.

Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

Input

The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made.

The second line contains a non-decreasing sequence, consisting of n integers a**i (|a**i| ≤ 104).

The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

Output

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

Examples

input

Copy

3 2
-1 -1 1

output

Copy

3

input

Copy

3 1
-1 -1 1

output

Copy

1

Note

In the first sample we can get sequence [1, 1, 1], thus the total income equals 3.

In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

题目大意

给定 n , k n,k ,有 n n 个数字,你可以改变 k k 次那数字的符号,每次一个。一定要用完 k k 次操作,问改变后 n n 个数的最大值是多少。

题目分析

其实写得时间比较多……但是写得快能过就行。用两次sort就行

首先,对输入进来的数升序排列。然后,遍历一遍改成正数,当次数到达k或者找到一个大于等于0的数的时候退出遍历。然后计算一下剩下还有多少次可以改变数字符号的操作。当还有剩下次数且次数为奇数(为偶数的时候,直接都对同一个数改变符号,耗尽操作次数。最后这个数的符号不变)时,寻找一下最小的数,然后改变那个数的符号就行。最后遍历求和

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 7;
int arr[maxn];
int main(int argc, char const *argv[]) {
  int n, k;
  scanf("%d%d", &n, &k);
  for(int i = 0; i < n; i++){
    scanf("%d", &arr[i]);
  }
  sort(arr, arr + n);
  int i = 0;
  while(i < k && i < n){
    if(arr[i] < 0) arr[i] = -arr[i];
    else break;
    i++;
  }
  k -= i;
  if(k > 0 && k % 2){
    sort(arr, arr + n);
    arr[0] = -arr[0]; 
  }
  long long ans = 0;
  for(int i = 0; i < n; i++)
    ans += arr[i];
  printf("%lld\n", ans);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/IT_w_TI/article/details/88144825