编程之美-买书问题-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;
}
    原文作者:zcliatb
    原文地址: https://blog.csdn.net/zcliatb/article/details/40820357
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞