USACO Buying Feed, II

洛谷 P2616 [USACO10JAN]购买饲料II Buying Feed, II

洛谷传送门

JDOJ 2671: USACO 2010 Jan Silver 2.Buying Feed, II

JDOJ传送门

Description

Farmer John needs to travel to town to pick up K (1 <= K <= 100)

The county feed lot has N (1 <= N <= 100) stores (convenientlynumbered 1..N) that sell feed. Each store is located on a segmentof the X axis whose length is E (1 <= E <= 350). Store i is atlocation X_i (0 < X_i < E) on the number line and can sell FJ asmuch as F_i (1 <= F_i <= 100) pounds of feed at a cost of C_i (1<= C_i <= 1,000,000) cents per pound. Amazingly, a given point onthe X axis might have more than one store.

What is the minimum amount FJ has to pay to buy and transport theK pounds of feed? FJ knows there is a solution.

It is best for FJ to buy one pound of feed from both the second andthird stores. He must pay two cents to buy each pound of feed fora total cost of 4. When FJ travels from 3 to 4 he is moving 1 unitof length and he has 1 pound of feed so he must pay 1*1 = 1 cents.

The total cost is 4+1+2 = 7 cents.

Input

* Line 1: Three space-separated integers: K, E, and N

* Lines 2..N+1: Line i+1 contains three space-separated integers: X_i,
F_i, and C_i

Output

* Line 1: A single integer that is the minimum cost for FJ to buy and
transport the feed

Sample Input

2 5 3 3 1 2 4 1 2 1 1 1

Sample Output

7

题目翻译:

FJ开车去买K份食物,如果他的车上有X份食物。每走一里就花费X元。 FJ的城市是一条线,总共E里路,有E+1个地方,标号0~E。 FJ从0开始走,到E结束(不能往回走),要买K份食物。 城里有N个商店,每个商店的位置是X_i(一个点上可能有多个商店),有F_i份食物,每份C_i元。 问到达E并买K份食物的最小花费。

题解:

转化成多重背包问题求解。

多重背包就是完全背包的升级版,从每种物品有无限件可以用变成有一个固定的数量,也可以用二进制优化一下,详见具体讲解。

本题可以采用这种动态规划的方式AC

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int dp[105];
int main()
{
    int n,e,k,x,f,c;
    scanf("%d%d%d",&k,&e,&n);
    for(int i=1;i<=k;i++)
        dp[i]=1<<30;
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d%d",&x,&f,&c);
        for(int j=k;j>=1;j--)
            for(int l=1;l<=f;l++)
            {
                if(l>j) 
                    break;
                dp[j]=min(dp[j],dp[j-l]+l*(c+e-x));
            }
    }
    printf("%d",dp[k]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/fusiwei/p/11295415.html