水果摊小买卖

水果摊小买卖

**题目描述:**小王手里有点闲钱,想着做点卖水果的小买卖。给出两个数组 m、n,用 m[i]代表第 i 个水果的成本价,n[i]代表第 i 水果能卖出的价钱,假如现在有本钱 k,试问最后最多能赚多少钱?
说明:
1 每种水果只需买一次,只能卖一次
2 数组 m、n 大小不超过 50
3 数组元素为正整数,不超过 1000
输入描述:
1 数组 m、n
2 本钱 k
备注:
1 首行输入逗号分隔的数组 m 的元素值
2 第二行输入逗号分隔的数组 n 的元素值
3 第三行输入本钱
输出描述:
最多能赚取多少钱。
示例 1
输入
4, 2, 6, 4
5, 3, 8, 7
15
输出
22
解题思路:
最直接的想法就是贪婪算法,每次选择当前成本能够购买的、利润最大的水果,然后卖出去,继续选择更新之后成本能够购买的、利润最大的水果,然后卖出去。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
using namespace std;

typedef struct ProductInfo{
	int cost;
	int profit;
	int isbuy=0;
}ProductInfo;

vector<int>StringToVector(const string& str){
	stringstream sstream(str);
	string token="";
	vector<int> vec_str;
	vec_str.clear();
	while(getline(sstream,token,',')){
		int num=0;
		for(int i=0;i<token.size();i++){
			num=10*num+token[i]-'0';
		}
		vec_str.push_back(num);
	}
	return vec_str;
}
bool Compare(const ProductInfo& a,const ProductInfo& b){
	return a.profit>b.profit;
}
bool CheckInfo(vector<ProductInfo>& productinfos,int cost_k){
	bool flag=false;
	for(int i=0;i<productinfos.size();i++){
		if(productinfos[i].isbuy==1){
			continue;
		}
		if(productinfos[i].profit<0){
			continue;
		}
		if(productinfos[i].cost<cost_k){
			flag=true;
			break;
		}
	}
	return flag;
}
int main(){
	string m="";
	while(getline(cin,m)){
		if (m.empty()) {
			break;
		}
		string n="";
		getline(cin,n);
		int k;
		cin>>k;
		vector<int> vec_m=StringToVector(m);
		vector<int> vec_n=StringToVector(n);
		vector<ProductInfo> productinfos;
		productinfos.clear();
		for(int i=0;i<vec_m.size();i++){
			ProductInfo productinfo;
			productinfo.cost=vec_m[i];
			productinfo.profit=vec_n[i]-vec_m[i];
			if(productinfo.profit<=0){
				continue;
			}
			productinfo.isbuy=0;
			productinfos.push_back(productinfo);
		}
		sort(productinfos.begin(),productinfos.end(),Compare);
		int cost_k=k;
		while(CheckInfo(productinfos,cost_k)){
			for(int i=0;i<productinfos.size();i++){
				if(productinfos[i].cost>cost_k){
					continue;
				}
				if(productinfos[i].profit<=0){
					continue;
				}
				if(productinfos[i].isbuy==1){
					continue;
				}
				cost_k+=productinfos[i].profit;
				productinfos[i].isbuy=1;
			}
		}
		cout<<cost_k<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值