类似背包的做法。
f[i][j]表示是否能放i个物品,价格为j
#include <cstdio> #include <iostream> #define N 8001 int n, sum; int a[201], f[201][N]; inline int read() { int x = 0, f = 1; char ch = getchar(); for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1; for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0'; return x * f; } int main() { int i, j, k; n = read(); for(i = 1; i <= n; i++) { a[i] = read(); sum += a[i]; } f[0][0] = 1; for(i = 1; i <= n; i++) for(j = n >> 1; j >= 1; j--) for(k = sum >> 1; k >= a[i]; k--) f[j][k] = f[j][k] | f[j - 1][k - a[i]]; for(i = j = sum >> 1; ; i--, j++) { if(f[n >> 1][i]) { printf("%d %d ", i, sum - i); return 0; } if(f[n >> 1][j]) { printf("%d %d ", sum - j, j); return 0; } } return 0; }