您的位置:首页 > 其它

HDU 1114 Piggy-Bank 动态规划完全背包

2012-09-15 17:45 639 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1114

题意:

  有T组测试数据,后面的E和F分别表示存钱罐空的时候的重量和满了的时候的重量 , 然后有个m ,

代表下面有 m 种钱币 , 每种钱币分别有他的面值和重量 , 要你求出当存钱罐满的时候 , 存钱罐中至少

有多少钱.

坑爹:

  因为他是要求出最少有多少钱 , 所以要 DP[ j ] = min ( DP [ j ] , DP[ j - cost ] + weight )

还有一点要注意的是DP数组的初始化 , 要初始化为最大值 , 因为它每次都要求最小的一种情况 , DP[0] = 0

是递推的一个开始.

解法:

  跟普通的完全背包差不多 , 平时的是要求最大的 , 而这个是要求最小的 , 反过来想就行了.

View Code

#include<iostream>
using namespace std;

const int maxn = 50000 + 10;
const int INF = 0x3fffffff;
int DP[maxn];
int n;

int min(int a,int b)
{
return a < b ? a : b;
}

void CompletePack(int cost,int weight)
{
int j;
for(j=cost; j<=n; j++)
{
DP[j] = min(DP[j] , DP[j-cost]+weight);
}
}

struct Node
{
int x;
int y;
};

struct Node A[maxn];

int main()
{
int T;
cin>>T;
while(T--)
{
//    memset(DP,0,sizeof(DP));

int a;
int b;
cin>>a>>b;
n = b - a;

int m;
cin>>m;

int i;

for(i=0; i<maxn; i++)
{
DP[i] = INF;
}
DP[0] = 0;
for(i=1; i<=m; i++)
{
cin>>A[i].x>>A[i].y;
}

for(i=1; i<=m; i++)
{
CompletePack(A[i].y , A[i].x);
}

if(DP
!= INF)
{
printf("The minimum amount of money in the piggy-bank is %d.\n",DP
);
}
else
{
printf("This is impossible.\n");
}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: