题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1059
题目大意:给定一个初始资金m,然后给定n种投资方案,每种投资方案中有投资额costi和利息vali,每年的投资就可以拿到全部利息,然后累加起来继续投资利滚利。问经过k年后最多拥有多少资金?
解题思路:这题我用了两种写法来解,一种是完全背包,一种是多重背包,前一种其实十分脑残,复杂度又高又不好写,但是我一开始想到的是这个解法,糗。将资金看成容量,将利息看成价值,每次处理完价值可累加到总容量中去,问题就转变成求k次背包后的最大容量。
状态转移方程:dp[j] = max(dp[j],dp[j-cost[i]]+val[i]) (cost[i]都是1000的倍数,可以全部除以1000,大幅度增加效率,1<=i<=n,cost[i]<=j<=m/1000).。总复杂度O(KVN)
测试数据:
3
10000 1
2
4000 400
5000 450
10000 1
2
8000 800
9000 900
代码:
//完全背包写法 #include <stdio.h> #include <string.h> #define MAX 110000 #define max(a,b) (a)>(b)?(a):(b) int ans,cost[MAX],val[MAX]; int n,m,year,dp[MAX],num[MAX]; int Solve_1A(int m,int year) { int i,j,k,t,tpm; for (t = 1; t <= year; ++t) { //二进制处理 tpm = m / 1000; memset(dp,0,sizeof(dp)); for (i = 1; i <= n; ++i) for (j = cost[i]; j <= tpm; ++j) dp[j] = max(dp[j],dp[j-cost[i]]+val[i]); m = m + dp[tpm]; } return m; } int main() { int i,j,k,t; scanf("%d",&t); while (t--) { scanf("%d%d",&m,&year); scanf("%d",&n); for (i = 1; i <= n; ++i) { scanf("%d%d",&cost[i],&val[i]); cost[i] = cost[i] / 1000; //都是1000的倍数 } ans = Solve_1A(m,year); printf("%d\n",ans); } }
//多重背包写法 #include <stdio.h> #include <string.h> #define MAX 110000 #define max(a,b) (a)>(b)?(a):(b) int tpcost[MAX],tpval[MAX]; int ans,cost[MAX],val[MAX]; int n,m,year,dp[MAX],num[MAX]; int Solve_1A(int m,int year) { int i,j,k,t,tpm; for (t = 1; t <= year; ++t) { //二进制处理 tpm = m / 1000; for (i = 1; i <= n; ++i) if (cost[i] == 0) num[i] = 0; else num[i] = tpm / cost[i]; for (k = 0,i = 1; i <= n; ++i) { if (num[i] == 0) continue; for (j = 0; (1<<j) <= num[i]; ++j) { num[i] = num[i] - (1<<j); tpcost[++k] = (1<<j) * cost[i]; tpval[k] = (1<<j) * val[i]; } tpcost[++k] = num[i] * cost[i]; tpval[k] = num[i] * val[i]; } //01背包 memset(dp,0,sizeof(dp)); for (i = 1; i <= k; ++i) for (j = tpm; j >= tpcost[i]; --j) dp[j] = max(dp[j],dp[j-tpcost[i]]+tpval[i]); m = m + dp[tpm]; } return m; } int main() { int i,j,k,t; scanf("%d",&t); while (t--) { scanf("%d%d",&m,&year); scanf("%d",&n); for (i = 1; i <= n; ++i) { scanf("%d%d",&cost[i],&val[i]); cost[i] = cost[i] / 1000; //都是1000的倍数 } ans = Solve_1A(m,year); printf("%d\n",ans); } }