天天看點

[挑戰程式設計競賽] POJ 3040 - Allowance

題意:

給定N,C分别代表面值的種類 和 每周至少要發的錢數。

接着輸入N行面值 和 對應面值的個數。

問給定這些錢最多能發多少周?

思路:

1、當對應面值 >= C時,不需要貪心,直接計算即可。

2、當對應面值 < C時,按面值從大到小貪心。貪心的過程不能浪費任何面值。

3、第二步結束後,顯然能不浪費的面值都已經拿完了,如果第二步貪心的結果val < C,那必然要浪費一個最小能滿足val + x > C的面值。

重複上述步驟即可。。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
//#define _Test
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int main()
{
    #ifdef _Test
        freopen("test.in", "r", stdin);
        freopen("test.out", "w", stdout);
        srand(time(NULL));
    #endif
    int N, C, ans;
    pair<int, int> cost[20];
    while(~scanf("%d %d", &N, &C))
    {
        for(int i = 0; i < N; i++)
        {
            scanf("%d %d", &cost[i].first, &cost[i].second);
        }
        ans = 0;
        sort(cost, cost+N);
        for(int i = 0; i < N; i++)
        {
            if(cost[i].first >= C)
            {
                ans += cost[i].first / C * cost[i].second;
                cost[i].second = 0;
            }
        }
        while(true)
        {
            int val = C;
            int sum = 0;
            for(int i = N - 1; i >= 0; i--)
            {
                if(val && cost[i].second)
                {
                    int k = min(val / cost[i].first, cost[i].second);
                    if(k)
                    {
                        val -= cost[i].first * k;
                        cost[i].second -= k;
                        sum += cost[i].first * k;
                    }
                }
            }
            for(int i = 0; i < N; i++)
            {
                if(val && cost[i].second && cost[i].first > val)
                {
                    val = 0;
                    sum += cost[i].first;
                    cost[i].second--;
                    break;
                }
            }
            if(val > 0) break;
            ans += sum / C;
        }
        printf("%d\n", ans);
    }
    return 0;
}