题目大意:
就是现在给出每个硬币的面值和重量,现在一个罐子里面装满了总重量为W的硬币,问最少的价值是多少
大致思路:
首先每个物品的体积就是重量,价值就是面值,要求完全装满,初始化f [ 1 ~ V ] 都为负无穷, f [ 0 ] 为0, 状态转移的时候取较小的值,每个物品可以放任意个故是一个完全背包
代码如下:
Result : Accepted Memory : 296 KB Time : 78 ms
/* * Author: Gatevin * Created Time: 2014/8/15 19:09:56 * File Name: haha.cpp */ #include<iostream> #include<sstream> #include<fstream> #include<vector> #include<list> #include<deque> #include<queue> #include<stack> #include<map> #include<set> #include<bitset> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cstring> #include<cctype> #include<cmath> #include<ctime> #include<iomanip> using namespace std; const double eps(1e-8); typedef long long lint; int f[10010]; int w[510]; int c[510]; int n,E,F,V; const int inf = 0x7fffffff; int main() { int t; scanf("%d", &t); while(t--) { scanf("%d %d", &E, &F); V = F - E; if(V < 0) { printf("This is impossible.\n"); continue; } scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d %d", &w[i], &c[i]); } f[0] = 0; for(int i = 1; i <= V; i++) f[i] = -inf; for(int i = 1; i <= n; i++) { for(int j = c[i]; j <= V; j++) { if(f[j] != -inf && f[j - c[i]] != -inf ) { f[j] = min(f[j], f[j - c[i]] + w[i]); continue; } if(f[j] == -inf && f[j - c[i]] != -inf) { f[j] = f[j - c[i]] + w[i]; continue; } } } if(f[V] == -inf) { printf("This is impossible.\n"); } else { printf("The minimum amount of money in the piggy-bank is %d.\n", f[V]); } } return 0; }