[Zhengqing] [1899] 985's Maximum Sum Challenge

Problem Description

985的最大和难题
Time limit: 1 SecMemory limit: 128 MB

Description

985 has 2 * n - 1 integers. Each time, he can change the signs of n of them, with no limit on the number of operations. What is the maximum sum he can obtain?

Input

The first line contains an integer t, indicating there are t test cases.
Each test case occupies two lines: the first line contains an integer n, and the next line contains 2*n-1 integers a[].
Note: 1 <= t <= 32, 1 <= n <= 1e3, -1e3 <= a[] <= 1e3.

Output

Output an integer representing the maximum sum that can be obtained.

Sample Input

1
2
3
4
5
2
2
1 1 1
2
-10 20 -10

Sample Output

1
2
3
40

Problem Analysis

Negative-number changes when n=3
(0 means negative, 1 means positive)
With one negative:

1
2
3
4
0 1 1 1 1
1 0 0 1 1
1 0 1 0 0
1 1 1 1 1

With two negatives:

1
2
3
4
0 0 1 1 1
0 1 0 0 1

1 1 1 1 1

With three negatives:

1
2
3
0 0 0 1 1

1 1 1 1 1

Summary of the pattern:

NegativesPositives
02n-1
nn-1
12n-2
n-1n
32n-4
n-3n+2
……

It can be observed that when n is odd,
all negative numbers can always be turned into positive numbers.
When n is even
each operation can change an even number of negative numbers
So if the number of negative numbers is even,
they can also all be turned into positive numbers.
When the number of negative numbers is odd, one number will always remain negative
(but it is not necessarily one of the original negative numbers)
To maximize the total sum,
we can make the number with the smallest absolute value negative.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h> 
int main() { 
    int T; 
    scanf("%d",&T); 
    while(T--) { 
        int n; 
        scanf("%d",&n); 
        int l=2*n-1; 
        int sum=0,cnt=0,res=99999999; 
        for(int i=0; i<l; i++) { 
            int t; 
            scanf("%d",&t); 
            if(t<0) { 
                cnt++; 
                t=-t; 
            } 
            if(res>t) 
                res=t; 
            sum+=t; 
        } 
        if(n&1||cnt%2==0) 
            printf("%d\n",sum); 
        else
            printf("%d\n",sum-2*res); 
    } 
    return 0; 
}

Problem link: ZZULI 1899 985’s Maximum Sum Problem

Loading...