编程语言:Java
题目链接:http://poj.org/problem?id=3040
题解:见注解
结果:AC
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
public static void main(String[] args) throws IOException {
int n = sc.nextInt();
int c = sc.nextInt();
coin[] a = new coin[n];
int[] used = new int[n];
for (int i = 0; i < n; i++) {
int v = sc.nextInt();
int num = sc.nextInt();
a[i] = new coin(v, num);
}
Arrays.sort(a, new Comparator<coin>() {
@Override
public int compare(coin o1, coin o2) {
return o2.value - o1.value;
}
});
int res = 0;
int i = 0;
//先去除所有能单独付款一周的金额
for (; i < n; i++) {
if (a[i].value >= c)
res += a[i].num;
else
break;
}
if (i >= n) {
//当所有金额均能单独付款,则直接输出结果
out.println(res);
} else {
for(;;){
Arrays.fill(used,0);
int cnt=c;
//找到最逼近于c金额的金额大小,当然如果此金额恰好可以用n张进行支付,就不需要使用小的金额了
for(int j=i;j<n;j++){
used[j]=Math.min(a[j].num,cnt/a[j].value);
cnt-=used[j]*a[j].value;
}
//如果此时离凑出c还有一段距离,那我们就需要选择一张恰好能付款的最小金额
if(cnt>0){
for(int j=n-1;j>=i;j--){
if(a[j].value>cnt&&(a[j].num-used[i])>0){
used[j]++;
cnt-=a[j].value;
break;
}
}
}
if(cnt>0)break;
int min=Integer.MAX_VALUE;
//确定这组付款组合的数量
for(int j=i;j<n;j++){
if(used[j]!=0){
min=Math.min(min,a[j].num/used[j]);
}
}
res+=min;
for(int j=i;j<n;j++){
a[j].num-=min*used[j];
}
}
out.println(res);
}
out.flush();
}
}
class coin {
int value;
int num;
public coin(int value, int num) {
this.value = value;
this.num = num;
}
}