pku1015
2014-02-18 14:32
204 查看
非常典型的动态规划题目,用别的方法会超时。
题目大意是说在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个人做一个平移,起始点也跟着变化(在程序中可以看到)。
题目大意是说在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; else return 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; else pos = 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; }
相关文章推荐
- pku1015 Jury Compromise解题报告
- pku 1015 Jury Compromise DP
- pku1015 Jury Compromise
- PKU ACM 1015 Jury Compromise (DP)
- PKU 1836 Alignment 解题报告
- 【OpenJudge9270】【Pku2440】【递推】DNA
- PKU_ACM_2388_Who's in the Middle
- 【codevs 1015】计算器的改良
- PKU 3177 Redundant Paths - 无向图的双连通分量和桥
- PAT(Advanced Level) 1015 - Reversible Primes(水题)
- pku动态规划题目列表
- Is It A Tree?[HDU1325][PKU1308]
- pku2286 The Rotation Game
- 100道动态规划——23 POJ 1015 Jury Compromise 恩,我也不知道怎么说这里的知识点
- pku1163---the triangle(三角形):动态规划题
- 九度OJ-1015-还是A+B
- pku 1062 昂贵的婚礼
- ZOJ 1403&&HDU 1015 Safecracker【暴力】
- 1015 Jury Compromise 解题报告
- hdu 1229&&九度oj1015 还是A+B