题目:
1 100 2 10 2 1 20 1 1
21HintCRB‘s mom buys 10 presents of first kind, and receives 2 × 10 + 1 = 21 candies.
题意:给了N种礼物,总共M块钱,每件礼物W【i】元,买x个第i种礼物可以得到A[I]*x+B[i]个糖果,问最多能得到多少糖果。
思路:看起来像完全背包,但有一些不同,完全背包是第i种物品的价值为P[i],也就是说买x个第i种物品能得到x*p[i]的价值,而这里是A[I]*x+B[i],所以要分是否是第一次买这个礼物,如果是第一次,那么增加的价值是A[i]+B[i],否则增加A[i].设dp[i][j][0]代表有j元钱,并且现在不买第i物品,dp[i][j][1]代表买这个物品,那么dp[i][j][0]=max(dp[i-1][j][0],dp[i-1][j][1]),dp[i][j][1]=max(dp[i][j-w[i]][0]+A[i]+B[i],dp[i][j-w[i]][1]+A[i]).
代码:
#include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include<climits> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> using namespace std; #define PB push_back #define MP make_pair #define REP(i,x,n) for(int i=x;i<(n);++i) #define FOR(i,l,h) for(int i=(l);i<=(h);++i) #define FORD(i,h,l) for(int i=(h);i>=(l);--i) #define SZ(X) ((int)(X).size()) #define ALL(X) (X).begin(), (X).end() #define RI(X) scanf("%d", &(X)) #define RII(X, Y) scanf("%d%d", &(X), &(Y)) #define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z)) #define DRI(X) int (X); scanf("%d", &X) #define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y) #define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z) #define OI(X) printf("%d",X); #define RS(X) scanf("%s", (X)) #define MS0(X) memset((X), 0, sizeof((X))) #define MS1(X) memset((X), -1, sizeof((X))) #define LEN(X) strlen(X) #define F first #define S second #define Swap(a, b) (a ^= b, b ^= a, a ^= b) #define Dpoint strcut node{int x,y} #define cmpd int cmp(const int &a,const int &b){return a>b;} /*#ifdef HOME freopen("in.txt","r",stdin); #endif*/ const int MOD = 1e9+7; typedef vector<int> VI; typedef vector<string> VS; typedef vector<double> VD; typedef long long LL; typedef pair<int,int> PII; //#define HOME int Scan() { int res = 0, ch, flag = 0; if((ch = getchar()) == '-') //判断正负 flag = 1; else if(ch >= '0' && ch <= '9') //得到完整的数 res = ch - '0'; while((ch = getchar()) >= '0' && ch <= '9' ) res = res * 10 + ch - '0'; return flag ? -res : res; } /*----------------PLEASE-----DO-----NOT-----HACK-----ME--------------------*/ int W[1005],A[1005],B[1005]; long long int dp[2005][2]; int main() {int T; RI(T); while(T--) { int M,N; RII(M,N); for(int i=1;i<=N;i++) RIII(W[i],A[i],B[i]); MS0(dp); for(int i=1;i<=N;i++) for(int m=0;m<=M;m++) { dp[m][0]=max(dp[m][0],dp[m][1]); if(m>=W[i]) dp[m][1]=max(dp[m-W[i]][0]+A[i]+B[i],dp[m-W[i]][1]+A[i]); else dp[m][1]=0; } printf("%I64d\n",max(dp[M][0],dp[M][1])); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 5410 CRB and His Birthday(动态规划)
原文地址:http://blog.csdn.net/u013840081/article/details/48132237