题意:就是把一堆浮点数分成两部分,要使得两部分的差值尽量小
思路:背包问题,由于是浮点数,没办法直接用数组记录下来,那么其实可以这样,转化为百分比,然后乘上1W倍,就转化为整数了
代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
const int N = 105;
const int M = 10005;
const int INF = 0x3f3f3f3f;
int n, a[N];
double p[N];
int dp[M], path[M];
void print(int u) {
if (u - a[path[u]] == 0) {
printf("%d", path[u]);
return;
}
print(u - a[path[u]]);
printf(" %d", path[u]);
}
int main() {
while (~scanf("%d", &n) && n) {
double sum = 0;
for (int i = 1; i <= n; i++) {
scanf("%lf", &p[i]);
sum += p[i];
}
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for (int i = 1; i <= n; i++) {
a[i] = p[i] / sum * 10000;
for (int j = 10000; j >= a[i]; j--) {
if (dp[j - a[i]] && !dp[j]) {
dp[j] = dp[j - a[i]];
path[j] = i;
}
}
}
int v = 0;
for (int i = 10000; i; i--) {
if (dp[i] && abs(10000 - 2 * v) > abs(10000 - 2 * i))
v = i;
}
print(v);
printf("\n");
}
return 0;
}