Explanation
Let's rule a simple case first. When can you not construct a valid solution?
Since the two sets have to have an equal sum, it's evident that both of them have to have half of . So, if , or the sum of the first positive integers isn't even, then a solution isn't possible. For each subset, we want its sum to be half of this sum, or
This, combined with the low bounds on , hints at a 0-1 Knapsack DP.
Instead of trying to make a combination of two subsets, let's try to make a combination of one, since the other set has to have all of the other elements.
If = the number of ways to make sum with the numbers from , then our transitions will be , if we don't include the current element, or we do.
Additionally, we could double count every single set. So, instead of counting up to , we'll count up until , ensuring that the th element is always placed in the second set.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int MOD = 1e9 + 7;int main() {int n;cin >> n;int sum_elem = n * (n + 1) / 2;
Java
import java.io.*;import java.util.*;public class TwoSets {static final int MOD = (int)1e9 + 7;public static void main(String[] args) {Kattio io = new Kattio();int N = io.nextInt();// The total sum of all N elements.
Python
import sysMOD = 10**9 + 7n = int(input())sum_elem = n * (n + 1) // 2 # Sum of elements in [1, ..., n]# If the sum of the elements is odd, then we can't split it evenly.if sum_elem % 2 == 1:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!