水果价格计算:最小值和最大值
题目描述
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of 'm' fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times.
When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most 'lucky' for him distribution of price tags) and the largest total price (in case of the most 'unlucky' for him distribution of price tags).
输入格式
The first line of the input contains two integer number 'n' and 'm' (1<=n,m<=100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains 'n' space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following 'm' lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to 'n'. Also it is known that the seller has in stock all fruits that Valera wants to buy.
输出格式
Print two numbers 'a' and 'b' (a<=b) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.
代码题解内容
Solution: 首先将所有水果按照单价从小到大排序,然后将Valera要买的水果按照单价从小到大依次匹配,这样得到的总价就是最小的。而对于最大的总价,只需要将所有水果按照单价从大到小排序,然后按照同样的方式匹配即可。
**时间复杂度:**O(nlogn),其中n为水果种类数。
原文地址: https://www.cveoy.top/t/topic/nP9M 著作权归作者所有。请勿转载和采集!