【华为2019年校园招聘】2019-4-17 软件题-水果摊小买卖

题目描述

小王手里有点闲钱,想着做点卖水果的小买卖,给出两个数组m,n,用m[i]表示第i个水果的成本价,
n[i]表示第i个水果能卖出的价钱,假如现在有本钱k元,试问最后最多能赚多少钱?

说明:
1. 每种水果只能买一次,只能卖一次;
2. 数组m,n大小不超过50;
3. 数组元素为正整数,不超过1000

输入描述

1. 数组m, n;
2. 本钱k

输出描述

最多能赚多少钱

示例

输入:
4,2,6,4
5,3,8,7
15

输出:
22

解题思路:
最直接的想法就是用贪婪算法,每次选择当前成本能够购买的、利润最大的水果,然后卖出去,继续选择更新之后成本能够购买的、利润最大的水果,然后卖出去。

样例代码

#include 
#include 
#include 
#include 
#include 
using namespace std;

//输入是一行字符,比如"4,2,6,4",输出是vector:{4,2,6,4}
vector str2vec(const string& str)
{
	stringstream sstr(str);
	string token;
	vector stu;
	while (getline(sstr, token, ','))
	{
		stu.push_back(token);
	}
	vector nums;
	for (int i = 0; i < stu.size(); ++i)
	{
		int num = 0;
		for (int j = 0; j < stu[i].size(); ++j)
		{
			num = num * 10 + stu[i][j] - '0';
		}
		nums.push_back(num);
	}
	return nums;
}

//定义商品信息:本钱bq,利润lr,是否被买过visit
struct good_info
{
	int bq;
	int lr;
	int visit = 0;
};

//定义比较函数,利润大的排前面
bool cmp(const good_info& left, const good_info& right)
{
	return left.lr > right.lr;
}

//检查遍历一遍之后的商品信息,看看遍历一遍之后赚到的钱能不能买到这次遍历过程中因为钱不够买不起的水果
bool check_vec(const vector& inp, int k)
{
	bool flag = false;
	for (int i = 0; i < inp.size(); ++i)
	{
		if (inp[i].visit == 1)
		{
			continue;
		}
		if (inp[i].lr <= 0)
		{
			continue;
		}
		
		//如果该次遍历的时候中间存在有的水果买不起,但是遍历完了赚到更多的钱之后,能够买得起了的情况,则还需要进行下一次遍历
		if (k > inp[i].bq)
		{
			flag = true;
			break;
		}
	}
	return flag;
}

int main(void)
{
	string m;
	while (getline(cin, m))
	{
		if (m.empty())
		{
			break;
		}
		string n;
		getline(cin, n);
		int k;
		cin >> k;

		vector vec_m = str2vec(m);
		vector vec_n = str2vec(n);
		
		//根据读取进来的本钱、售价,计算商品的信息
		vector profit;
		for (int i = 0; i < vec_m.size(); ++i)
		{
			good_info gi;
			gi.bq = vec_m[i];
			gi.lr = vec_n[i] - vec_m[i];
			if (gi.lr <= 0)
			{
				continue;
			}
			gi.visit = 0;
			profit.push_back(gi);
		}
		std::sort(profit.begin(), profit.end(), cmp);  //按照利润从大到小排序,优先买进利润高的水果

		int f = k;
		
		while (check_vec(profit, f))
		{
			//按照利润从高到低遍历所有水果,能买就买,买完就买收取利润,买不起就跳过,留待下次有更多钱了再返回来查看
			for (int i = 0; i < profit.size(); ++i)
			{
				if (f < profit[i].bq)
				{
					continue;
				}
				if (profit[i].lr <= 0)
				{
					continue;
				}
				if (profit[i].visit == 1)
				{
					continue;
				}
				f = f + profit[i].lr;
				profit[i].visit = 1;
			}
		}

		cout << f << endl;
	}

	return 0;
}

你可能感兴趣的:(C/C++)