Divide into 2 groups#11339

Divide into 2 groups (Editorial)

Note that if the numbers and n - 3 are placed in one group, and n - 1 and n - 2 are placed in the other (so that the sum of numbers in each group is equal), the problem reduces to a similar problem of smaller size, namely, dividing the numbers 1, 2, ..., n - 4 into two groups.

For n \le 3, the numbers are divided into groups as follows:

If the sum of all numbers from to is even, they can be divided into two groups with equal sums.

If the sum of all numbers from to is odd, they can be divided into two groups with a sum difference of .

Example

Let n = 10. The numbers are placed into groups as follows:

Let n = 11. The numbers are placed into groups as follows:

Algorithm implementation

Read the input value .

scanf("%d", &n);

Initialize the initial sums of the numbers in the groups, s_1 and s_2 to .

s1 = s2 = 0;

Iterate through the numbers from down to .

for (i = n; i > 0; i--)

If s_1 < s_2, place the number into the first group. Otherwise, place the number into the second group.

  if (s1 < s2)
  {
    s1 += i;
    a.push_back(i);
  }
  else
  {
    s2 += i;
    b.push_back(i);
  }

Print the sizes of the groups.

printf("%d %d\n", a.size(), b.size());

Print the numbers of the first group.

for (i = 0; i < a.size(); i++)
  printf("%d ", a[i]);
printf("\n");

Print the numbers of the second group.

for (i = 0; i < b.size(); i++)
  printf("%d ", b[i]);
printf("\n");