您的位置:首页 > 其它

[挑战程序设计竞赛] POJ 3040 - Allowance

2014-12-19 11:56 302 查看
题意:

给定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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息