A - Fruits
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).
Input
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.
Output
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.
Examples
Input
5 3
4 2 1 10 5
apple
orange
mango
Output
7 19
Input
6 5
3 5 1 6 8 1
peach
grapefruit
banana
orange
orange
Output
11 30
思路:贪心算法
将价格排序,将每种水果的个数排序,最大值即数量最多乘以价格最大,最小值即数量最少乘以价格最大。。。其中用到Map容器去重。
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
sc.nextLine();
Map<String,Integer> map = new HashMap<>();
int temp = 0;
for (int i = 0; i < m; i++) {
String str = sc.nextLine();
if(map.containsKey(str)) {
temp = map.get(str);
map.put(str, temp+1);
}else {
map.put(str , 1);
}
}
Set<Entry<String, Integer>> set = map.entrySet();
int[] arr2 = new int[set.size()];
int index= 0;
for (Entry<String, Integer> ss : set) {
arr2[index] = ss.getValue();
index++;
}
Arrays.sort(arr2);//从小到大
long min = 0;
long max = 0;
for (int i = 0; i < arr2.length; i++) {
min += arr2[arr2.length-1-i] * arr[i];
max += arr2[arr2.length-1-i] * arr[arr.length-i-1];
}
System.out.println(min+" "+max);
sc.close();
}
}