题目的意思是,从n个数对<Pi, Di>中选出m个,要求:
1. |Sum{Pi} - Sum{Di}|最小
2. 满足1的情况下,Sum{Pi + Di}最大
并且输出这m个的编号。
这里n<=200, m<=20, 0<=Pi,Di<=20
解法:三维动态规划。设s[i] = Pi - Di, t[i] = Pi + Di,
f[i][j][k]表示从前i个人中选出j个人,满足它们的s值之和等于k,最大的t值之和,如果无解则等于-1。问题的解就是满足f[n][m][k]有解的绝对值最小的k。
动态转移方程:
对应第i个人选和不选两种情况,f[i][j][k] = max { f[i-1][j][k], f[i-1][j-1][k-s[i]]+t[i] }
其中1<=i<=n, 1<=j<=min(i,20), -20*j<=k<=20*j
初始条件:f[i][0][0]=0, 其他都为-1.
注意考虑f无解的情况,转移时需要做一些条件判断。
由于题目还要求记录下m个人具体的编号,所以还需要一个三维数组path[i][j][k]记录对应f[i][j][k]的最后一个人编号,最后沿着path回退即可构造答案序列。
需要注意的是k有可能是负值,所以实现时要将f的第三维度都加上400,保证下标是正数。
附上AC代码:
#include <iostream>
#define MIN(x, y) ((x) < (y) ? (x) : (y))
using namespace std;
int s[201], t[201], f[201][21][801], path[201][21][801], prosecution[201], defense[201];
int main()
{
int n, m, nCase;
for (nCase = 1;; nCase++)
{
cin >> n >> m;
if (n == 0 && m == 0)
break;
for (int i = 1; i <= n; i++)
{
cin >> prosecution[i] >> defense[i];
s[i] = prosecution[i] - defense[i];
t[i] = prosecution[i] + defense[i];
}
/* f[i][0][0] = 0, all the others = -1 */
for (int i = 0; i <= 200; i++)
{
for (int j = 0; j <= 20; j++)
{
for (int k = 0; k <= 800; k++)
{
if (j == 0 && k == 400)
f[i][j][k] = 0;
else
{
f[i][j][k] = -1; /* no solution */
}
}
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= MIN(i, 20); j++)
{
for (int k = -20 * j; k <= 20 * j; k++)
{
k += 400;
/* not select */
if (f[i - 1][j][k] != -1)
{
f[i][j][k] = f[i - 1][j][k];
path[i][j][k] = path[i - 1][j][k];
}
/* select */
if (f[i - 1][j - 1][k - s[i]] != -1 && f[i - 1][j - 1][k - s[i]] + t[i] > f[i][j][k])
{
f[i][j][k] = f[i - 1][j - 1][k - s[i]] + t[i];
path[i][j][k] = i;
}
k -= 400;
}
}
}
for (int i = 0; i <= 400; i++)
{
if (f[n][m][400 - i] != -1 || f[n][m][400 + i] != -1)
{
int optK = (f[n][m][400 - i] > f[n][m][400 + i] ? 400 - i : 400 + i);
int ans[21], sum_prosecution = 0, sum_defense = 0;
/* rebuild the path */
int ii = n, jj = m, kk = optK;
for (int j = 1; j <= m; j++)
{
ans[j] = path[ii][jj][kk];
ii = ans[j] - 1;
jj--;
kk -= s[ans[j]];
sum_prosecution += prosecution[ans[j]];
sum_defense += defense[ans[j]];
}
/* write result */
cout << "Jury #" << nCase << endl;
cout << "Best jury has value " << sum_prosecution << " for prosecution and value " << sum_defense << " for defence:" << endl;
/* write path */
for (int j = m; j >= 1; j--)
cout << ' ' << ans[j];
cout << endl << endl;
break;
}
}
}
return 0;
}