I'm working on a combinatorics problem where I need to compute how many ways the set {1, 2, ..., n} can be divided into two subsets with equal sum, such that every number from 1 to n is in exactly one of the two subsets. The two subsets are unordered (i.e., {A, B} is considered the same as {B, A}).
Constraints:
nis between 1 and 500.- Result must be modulo 10⁹ + 7.
Example:
For n = 7, the valid partitions are:
{1, 3, 4, 6} and {2, 5, 7} {1, 2, 5, 6} and {3, 4, 7} {1, 2, 4, 7} and {3, 5, 6} {1, 6, 7} and {2, 3, 4, 5} So the answer is 4.
What I’ve tried:
I noticed the total sum S = n(n+1)/2, and if S is odd, the answer is 0. I also tried adapting a dynamic programming approach similar to the classic subset sum problem:
MOD = 10**9 + 7 n = 7 # Idea: dp[i][j] = number of ways to pick a subset from {1..i} with sum j dp = [[0] * (target + 1) for _ in range(n + 1)] # Initialize... But I'm not sure how to:
- Avoid overcounting mirrored partitions.
- Efficiently handle the modulo math.
- Translate the total number of equal-sum partitions from this DP table.
Question:
How should I modify or complete this DP to correctly count unique equal-sum bipartitions of {1..n}? Is there a standard trick (e.g. halving final count, inclusion-exclusion, etc.) I should be using here?
c++when there is no C++ involved in the body of the question?