pku1015

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

题目大意是说在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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值