AcWing 1603 integer set division

Title description:
Given a set containing N positive integers, please divide it into two sets A1 and A2, where A1 contains n1 elements and A2 contains n2 elements.

The collection can contain the same elements.

Let S1 denote the sum of all elements in the set A1, and S2 denote the sum of all the elements in the set A2.

Please divide it properly so that |n1−n2| is as small as possible, and on this basis |S1−S2| is as large as possible.

Input format

The first line contains the integer N.

The second line contains N positive integers.

Output format

Output |n1−n2| and |S1−S2| in one line, separated by a space between the two numbers.

data range

2≤N≤10^5 to
ensure that each element in the set and the sum of all elements are less than 2^31.

Input example 1:

10
23 8 10 99 46 2333 46 1 666 555

Output sample 1:

0 3611

Input example 2:

13
110 79 218 69 3721 100 29 135 2 6 13 5188 85

Output sample 2:

1 9359
#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAX = 1e5 + 9;

int a[MAX];
int n;

int main()
{
    scanf("%d", &n);

    for(int i = 0; i < n; i++)
        scanf("%d", &a[i]);

    sort(a, a + n);

    int n1, n2, sum1, sum2;
    sum1 = sum2 = 0;

    n1 = n / 2;
    n2 = n - n1;

    for(int i = 0; i < n1; i++)
        sum1 += a[i];


    for(int i = n1; i < n; i++)
        sum2 += a[i];

    printf("%d %d\n", n2 - n1, sum2 - sum1);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/113632054