时间限制:C/C++ 语言:1000MS,其他语言3000MS
内存限制:C/C++ 语言:65536KB,其他语言589824KB
大意是:
小B去商店购物,列了物品清单。但货架上物品的价签尚未标上。根据购买清单,算出最好和最坏情况下所需费用。
输入:
输入为多组。每组第一行为整数n和m(1<=n,m<=1000),分别表示价签数和购买清单所列物品数。第二行为空格分隔的n个整数,表示货架上各类物品价格(价格<100000)。后面m行为购买清单中物品的名称,名称为非空的不超过32个拉丁字母的字符串,保证清单中物品种类数不超过n,且商店有小B想要购买的所有物品。
输出:
对每组测试数据,输出两数a,b,表示购买清单上所有物品所需最小和最大费用
样例输入:
5 3
4 2 1 10 5
apple
orange
mango
6 5
3 5 1 6 8 1
peach
grape
banana
orange
orange
样例输出:
7 19
11 30
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
static int n; // 价签数
static int m; // 物品数
static Stuff[] array;
static Map<String, Stuff> map;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
n = in.nextInt();
m = in.nextInt();
int[] b = new int[n]; // 价格
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
String nextline = in.nextLine();
map = new HashMap<String, Stuff>();
for (int i = 0; i < m; i++) {
String str = in.nextLine();
if (map.containsKey(str)) {
map.get(str).count++;
} else {
Stuff s = new Stuff(str);
map.put(str, s);
}
}
array = new Stuff[map.size()];
int u = 0;
for (String key : map.keySet()) {
array[u] = map.get(key);
u++;
}
Arrays.sort(array, new StuffCom());
Arrays.sort(b);
//最小费用
getPrice(b);
int[] a = new int[b.length];
for (int j = 0; j < b.length; j ++) {
a[j] = b[b.length - 1 - j];
}
// 最大费用
getPrice(a);
}
in.close();
}
public static void getPrice(int[] b) {
int count = 0;
for (int i = 0; i < array.length; i++) {
int arrcount = array[i].count;
while(arrcount!= 0 ) {
count += b[i];
arrcount--;;
}
}
System.out.println(count);
}
}
import java.util.Comparator;
public class StuffCom implements Comparator<Stuff>{
@Override
public int compare(Stuff s1, Stuff s2) {
return s2.count - s1.count ; //根据count反向排序
}
}
class Stuff {
String name;
int count;
public Stuff (String name) {
this.name = name;
this.count = 1;
}
}