过年啦!小B高兴的不行了,她收到了很多红包,可以实现好多的愿望呢。小B可是对商店货架上心仪的货物红眼好久了,只因囊中羞涩作罢,这次她可是要大大的shopping一番。小B想去购物时,总是习惯性的把要买的东西列在一个购买清单上,每个物品单独列一行(即便要买多个某种物品),这次也不例外。

include "stdafx.h"

#include<iostream>
#include<vector>
#include <algorithm>  
#include<iomanip>
#include<string>
#include<set>

using namespace std;

struct Good
{
	string name;
	int num; 
};
bool compareGood(Good g1,Good g2)
{
	return g1.num > g2.num;
}
bool compareLess(int num1, int num2)
{
	return num1 < num2;
}
bool compareMore(int num1, int num2)
{
	return num1 > num2;
}
int main()
{
	int n, m;
	while (cin>>n>>m)
	{
		vector<int> prices;
		vector<Good>list;
		for (int i = 0; i < n; i++)
		{
			int temp;
			cin >> temp;
			prices.push_back(temp);
		}
		for (int i = 0; i < m; i++)
		{
			string name;
	
			cin >> name;
			bool find = false;
			for (int j = 0; j < list.size(); j++)
			{
				if (list[j].name == name)
				{
					list[j].num++;
					find = true;
					break;
				}
			}
			if (find == false)
			{

				Good good;
				good.name=name;
				good.num = 1;
				list.push_back(good);
			}
		}

	
		stable_sort(list.begin(), list.end(), compareGood);
	

		int less=0;
		stable_sort(prices.begin(), prices.end(),compareLess);
		for (int i = 0; i < list.size(); i++)
		{
		//	cout <<"最低:" <<list[i].name << " " << list[i].num<<" "<<prices[i] << endl;
			less += (list[i].num)*prices[i];
		}

		

		int more = 0;
		stable_sort(prices.begin(), prices.end(),compareMore);
		for (int i = 0; i < list.size(); i++)
		{
		//	cout << "最高:" << list[i].name << " " << list[i].num << " " << prices[i] << endl;
			more += (list[i].num)*prices[i];
		}
		cout << less << " " << more << endl;
	}
	
}

熟练使用C++中提供的算法,即能提高效率,又能提高准确性

原文地址:https://www.cnblogs.com/wdan2016/p/6849722.html