# Logue P4104 [HEOI2014] balance (dp Combinatorial Mathematics)

Keywords: C++

## Sol

The topic can be converted into the number of \ (K \) selected from \ ([1, 2n + 1] \), so that the sum is \ ((n+1)k \).

Another conversion: divide \ ((n+1)k \) into \ (K \) numbers, so that each number can be in the range of \ ([1, 2n + 1] \)

At this time, you can use the idea of integer division dp (but I still can't think of goose.. )

Because each number is different from each other, we can regard the number divided in each stage as constant

Set \ (f[i][j] \) to represent the number of previous \ (I \) and the number of schemes that meet the conditions.

Let's consider whether the minimum number is \ (1 \)

I f not \ (1 \), map to all numbers \ (- 1 \), that is \ (f[i][j - i] \)

I f \ (1 \), it is equal to \ (+ 1 \) for all numbers of \ (f[i - 1][j - (i-1)] \), and \ (1 \) is added at the top, with the scheme of \ (f[i - 1][j - i] \)

Then subtract the scheme whose maximum number exceeds \ (2n+1 \), that is \ (f[i][j - (2n + 2)] \)

Complexity \ (O(Tnk^2) \)

```#include<bits/stdc++.h>
#define Fin(x) freopen(#x".in", "r", stdin);
using namespace std;
const int MAXN = 50001;
int mod;
template<typename A, typename B> inline bool chmax(A &x, B y) {return x < y ? x = y, 1 : 0;}
template<typename A, typename B> inline bool chmin(A &x, B y) {return x > y ? x = y, 1 : 0;}
template<typename A, typename B> inline A mul(A x, B y) {return 1ll * x * y % mod;}
template<typename A, typename B> inline void add2(A &x, B y) {x = x + y >= mod ? x + y - mod : x + y;}
template<typename A, typename B> inline int add(A &x, B y) {return x + y >= mod ? x + y - mod : x + y;}
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int fp(int a, int p) {
int base = 1;
while(p) {
if(p & 1) base = mul(base, a);
a = mul(a, a);  p >>= 1;
}
return base;
}
int inv(int x) {
return fp(x, mod - 2);
}
int f[101][100001];
void solve() {
memset(f, 0, sizeof(f));
f[0][0] = 1;
for(int j = 1; j <= (N + 1) * K; j++)
for(int i = 1; i <= min(j, K); i++) {
f[i][j] = add(f[i][j - i], f[i - 1][j - i]);
if(j >= 2 * N + 2) add2(f[i][j], -f[i - 1][j - (2 * N + 2)] + mod);
}
cout << f[K][(N + 1) * K] << '\n';
}
signed main() {
for(int T = read(); T--; solve());
return 0;
}```

Posted by Bea on Sun, 01 Dec 2019 09:37:34 -0800