POJ 3040 Allowance

编程语言: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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值