POJ - 1015 Jury Compromise

input:
4 2 1 2 2 3 4 1 6 2 0 0
output:
Jury #1 Best jury has value 6 for prosecution and value 4 for defence: 2 3
题目大意:
一个人分别对两个派有两个好感度(P,D),让你选m个人,让要m个人的D(j)-P(j)的绝对值(差值和)最小, 若前个条件为相等则选m个人的D(j)+P(j)(和值和)最大的。
分析:
dp。dp[j][k]=选择j个人j个人的差值和为k的最大和值和。k(差值和)是有可能为负数,所以要用偏移量为了保 证全都可行,将偏移量设置成m*20(最大差值为20,那么最大且为负数的最大差值和是-m*20,所以将偏移量设 置成m*20),如此设置后,dp[0][m*20]即为原本的dp[0][0]。
code:
#define frp
//#include<bits/stdc++.h>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
const ll INF = 0x3f3f3f3f;
const ll inf = 0x7fffff;
const int maxn = 1000;
const int MAXN = 1000;
int dp[50][MAXN], D[500], P[500];
int path[50][MAXN], ans[MAXN];
int n, m;
bool check(int j, int k, int i) {
while (j > 0 && path[j][k] != i) {
k -= (P[path[j][k]] - D[path[j][k]]);
j--;
}
return j == 0;
}
void solve() {
int cnt = 1;
while (cin >> n >> m && (m || n)) {
for (int i = 0; i < n; i++) {
cin >> P[i + 1] >> D[i + 1];
}
memset(dp, -1, sizeof(dp));//默认所有的方案都不可行.
memset(path, 0, sizeof(path));
int minInd = m * 20;
dp[0][minInd] = 0;//初始状态。
for (int j = 1; j < m + 1; j++) {
for (int k = 0; k < minInd * 2; k++) {
if (dp[j - 1][k] >= 0) {//当且仅当方案可行的时候可以进行状态转移
for (int i = 1; i < n + 1; ++i) {
if (dp[j - 1][k] + P[i] + D[i] > dp[j][k + P[i] - D[i]]) {
if (check(j - 1, k, i)) {//看此方之前是否选过i这个人
dp[j][k + P[i] - D[i]] = dp[j - 1][k] + P[i] + D[i];
path[j][k + P[i] - D[i]] = i;
}
}
}
}
}
}
int i = minInd, j = 0;
while (dp[m][i + j] < 0 && dp[m][i - j] < 0) {
j++;
}
int k = dp[m][i + j] > dp[m][i - j] ? i + j : i - j;
cout << "Jury #" << cnt++ << endl;
cout << "Best jury has value " << (k - minInd + dp[m][k]) / 2 << " for prosecution and value "
<< (dp[m][k] - k + minInd) / 2 << " for defence:" << endl;
for (int i = 1; i < m + 1; i++) {
ans[i] = path[m - i + 1][k];
k -= P[ans[i]] - D[ans[i]];
}
sort(ans + 1, ans + 1 + m);
for (int i = 1; i < m + 1; i++) {
cout << " " << ans[i];
}
cout << endl << endl;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef frp
freopen("D:\\coding\\c_coding\\in.txt", "r", stdin);
// freopen("D:\\coding\\c_coding\\out.txt", "w", stdout);
#endif
solve();
return 0;
}

浙公网安备 33010602011771号