1. 程式人生 > >【Codeforces 1106B】Lunar New Year and Food Ordering

【Codeforces 1106B】Lunar New Year and Food Ordering

font pair this else force arr except .com rabl

【鏈接】 我是鏈接,點我呀:)
【題意】


給你n個菜以及每個人需要的菜以及數量
如果某個人無法滿足它對菜的需求的話
就用價格比較低的菜來填充它的要求。
(如果價格低的菜不夠了,那麽就直接輸出0)
否則輸出每個人的消費總量

【題解】


把所有的菜按照價格升序排序.
對於每一個顧客的kind,num
先減少菜的數量。
然後定義一個變量last
表示last之前的菜都已經售空(排序後,每個人可能會有多余的部分,要用前面最小的若幹部分填充)
所以每個人都會讓價格低的前面的一部分菜清空。
我們每次給某個顧客填充的時候,只要從那個零界點開始填充就好
然後不要一個訂單一個訂單(單個)的處理
而應該一個菜一個菜的遍歷

這樣復雜度才是線性的。

【代碼】

import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;


public class Main {
    
    static class Pair implements Comparable<Pair>{
        int x,id;
        
        public Pair(int x,int id) {
            this.x = x;this.id = id;
        }

        @Override
        public int compareTo(Pair arg0) {
            if (arg0.x==this.x)
                return this.id-arg0.id;
            else return this.x-arg0.x;
        }
        
    }
    
    static int n,m;
    static int rest[],Cost[],l[],r[];
    static Pair a[];
    
    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        n = in.nextInt();m = in.nextInt();
        rest = new int[n];
        a = new Pair[n];
        l = new int[n+10];
        r = new int[n+10];
        Cost = new int[n+10];
        
        for(int i = 0;i < n;i++) rest[i]= in.nextInt();
        for (int i = 0;i < n;i++) {
            a[i] = new Pair(0,i);
            a[i].x = in.nextInt();
            Cost[i] = a[i].x;
        }
        Arrays.sort(a);
        int last = 0;
        
        for (int i = 1;i <= m;i++) {
            long cost = 0;
            int kind,num;
            kind = in.nextInt();num = in.nextInt();
            kind--;
            int temp = Math.min(num, rest[kind]);
            rest[kind]-=temp;
            num-=temp;
            cost += 1l*temp*Cost[kind];
            
            while(num>0 && last <n) {
                temp = Math.min(num, rest[a[last].id]);
                rest[a[last].id]-=temp;
                num-=temp;
                cost+=(long)1l*temp*Cost[a[last].id];
                if (rest[a[last].id]==0) {
                    last++;
                }
            }
            if (num!=0) cost = 0;
            System.out.println(cost);
        }
    }

}

【Codeforces 1106B】Lunar New Year and Food Ordering