编程之美-买书问题-hashmap存储

考虑到有5种书的输入,转换为字符串,用hashmap方式存储中间过程。

采用递归方式计算。

#include <iostream>
#include <string>
#include <hash_map>
#include <algorithm>
using namespace std;
using namespace stdext;

hash_map<string,double> ans;
hash_map<string,double>::const_iterator zero;
typedef pair<string,double> mypair;

string myinttostring(int a,int b,int c,int d,int e)
{
	// sort a,b,c,d,e
	int v[5];
	v[0]=a;v[1]=b;v[2]=c;v[3]=d;v[4]=e;
	sort(v,v+5);
	a=v[4];b=v[3];c=v[2];d=v[1];e=v[0];

	char vv[1000];
	sprintf_s(vv,999,"%d_%d_%d_%d_%d",a,b,c,d,e);
	string tmp(vv);
	return tmp;
}
double calculate(int a,int b,int c,int d,int e)
{
	// sort a,b,c,d,e
	int v[5];
	v[0]=a;v[1]=b;v[2]=c;v[3]=d;v[4]=e;
	sort(v,v+5);
	a=v[4];b=v[3];c=v[2];d=v[1];e=v[0];
	
	double max = 1000000000;
	double cur;
	string tmp;
	if(e >= 1){
		tmp = myinttostring(a-1,b-1,c-1,d-1,e-1);
		zero = ans.find(tmp);
		if(zero != ans.end())
			cur = 30 + zero->second;
		else{
			cur = calculate(a-1,b-1,c-1,d-1,e-1);
			cur += 30;
			ans.insert(mypair(tmp,cur));
			
		}
		if(cur < max)
			max = cur;
	}
	if(d >= 1){
		tmp = myinttostring(a-1,b-1,c-1,d-1,e);
		zero = ans.find(tmp);
		if(zero != ans.end())
			cur = 25.6 + zero->second;
		else{
			cur = calculate(a-1,b-1,c-1,d-1,e);
			cur += 25.6;
			ans.insert(mypair(tmp,cur));
		}
			
		if(cur < max)
			max = cur;
	}
	if(c >= 1){
		tmp = myinttostring(a-1,b-1,c-1,d,e);
		zero = ans.find(tmp);
		if(zero != ans.end())
			cur = 21.6 + zero->second;
		else{
			cur = calculate(a-1,b-1,c-1,d,e);
			cur += 21.6;
			ans.insert(mypair(tmp,cur));
		}
			
		if(cur < max)
			max = cur;
	}
	if(b >= 1){
		tmp = myinttostring(a-1,b-1,c,d,e);
		zero = ans.find(tmp);
		if(zero != ans.end())
			cur = 15.2 + zero->second;
		else{
			cur = calculate(a-1,b-1,c,d,e);
			cur += 15.2;
			ans.insert(mypair(tmp,cur));
		}	
		if(cur < max)
			max = cur;
	}
	if(a >= 1){
		tmp = myinttostring(a-1,b,c,d,e);
		zero = ans.find(tmp);
		if(zero != ans.end())
			cur = 8 + zero->second;
		else{
			cur = calculate(a-1,b,c,d,e);
			cur += 8;
			ans.insert(mypair(tmp,cur));
		}	
		if(cur < max)
			max = cur;
	}
	return max;
}
int main()
{
	
	string tmp = myinttostring(0,0,0,0,0);
	ans.insert(mypair(tmp,0));

	int a,b,c,d,e;
	cin>>a>>b>>c>>d>>e;

	cout<<calculate(a,b,c,d,e)<<endl;

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值