pku1015

来源:互联网 发布:手机淘宝卖家中心在哪 编辑:程序博客网 时间:2024/06/14 08:06

非常典型的动态规划题目,用别的方法会超时。

题目大意是说在n个人中选取m个人做为陪审团,而每个人有D和P两个值(最大为20最小为0),选出陪审团的规则是:假设选出m个人的陪审团,要求其中所有人的D-P的绝对值为最小,如果有相同的,则需要D+P最大。

用动态规划首先要找出状态,设f(m,k) = max,表示m个人,k为其D-P的最小值,max为D+P的最大值。则状态转移方程:f(m-1,k)) +add(x) = f(m,k+sub(x))。其中x表示某个没在f(m-1,k)中的人,而sub(x)为x的D-P,add(x)为x的D+P。在程序中如果方程右边原来的值小于左边,则将左边的值赋给右边。

在编程中注意f(m,k)中k可能小于0,所以根据m个人做一个平移,起始点也跟着变化(在程序中可以看到)。

#include<iostream>。#include<algorithm>using namespace std;int sub[200];int add[200];int temp[20];int result[21][801];int solution[21][801];bool insolution(int i,int j,int k){while(j>0 && solution[j][k] != i){k -= sub[solution[j][k]];j--;}if(j == 0)return false;elsereturn true;}int main(){int n,m,p,d,rot;int times = 0;while(cin>>n>>m){if(n == 0 || m == 0)break;int cnt =0;while(n){cin>>p>>d;add[cnt] = d+p;sub[cnt] = d-p;--n;++cnt;}memset(result,-1,sizeof(result));memset(solution,0,sizeof(solution));rot = m*20;result[0][rot] = 0;for(int j=0;j<m;++j){for(int k =0;k<=2*rot;k++){if(result[j][k] >=0){for(int i = 0;i<cnt;i++){if(result[j][k]+add[i] > result[j+1][k+sub[i]]){if(!insolution(i,j,k)){result[j+1][k+sub[i]] = result[j][k]+add[i];solution[j+1][k+sub[i]] = i;}}}}}}int jj=0;int pos;while(result[m][rot+jj]<0&&result[m][rot-jj]<0)++jj;if(result[m][rot+jj]>result[m][rot-jj])pos = rot+jj;elsepos = rot-jj;cout<<"Jury #"<<(++times)<<endl;cout<<"Best jury has value "<<(result[m][pos]+rot-pos)/2<<" for prosecution and value "<<(result[m][pos]+pos-rot)/2<<" for defence:"<<endl;for(int i = 0;i<m;i++){temp[i] = solution[m-i][pos];pos -= sub[temp[i]];}sort(temp,temp+m);for(int i = 0;i<m;i++){cout<<" "<<(temp[i]+1);}cout<<endl;}return 0;}


0 0
原创粉丝点击