Codeforce - 262 - B. Roma and Changing Signs

B. Roma and Changing Signs
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard 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 ai (|ai| ≤ 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
3 2
-1 -1 1
output
3
input
3 1
-1 -1 1
output
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 個數之和最大。操作:正負變換。

AC代碼思路:貪心題,需要分清楚一下幾個情況。1) n 個數全是非負數。2) k 大於負數的個數時。3) k 小於負數的個數時。

AC代碼:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n,k;
    cin>>n>>k;
    int a[n+5];
    int neg=0,flag=0;
    for (int i=1;i<=n;i++)
    {
        cin>>a[i];
        if (a[i]<0) neg++;
        if (!a[i]) flag=1;
    }

    long long sum=0;
    if (!neg)
    {
        for (int i=1;i<=n;i++) sum+=a[i];
        if (k%2) sum-=2*a[1];
    }
    else {
    if (neg>=k)
    {
        for (int i=1;i<=k;i++)
        {
            if (a[i]<0) sum+=-1*a[i];
            else sum+=a[i];
        }
        for (int i=k+1;i<=n;i++) sum+=a[i];
    }
    else
    {
        for (int i=1;i<=n;i++)
        {
            if (a[i]<0) sum+=-1*a[i];
            else sum+=a[i];
        }
        if (!flag && (k-neg)%2)  sum+=2*(fabs(a[neg])<a[neg+1]?a[neg]:-1*a[neg+1]);
    }
    }
    cout<<sum;
}

P.S. 附幾組樣例:
1)
6 6
0 1 1 1 1 1
2)
6 6
-1 0 1 1 1 1
3)
6 5
-1 1 1 1 1 1

發佈了47 篇原創文章 · 獲贊 28 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章