DP之背包问题详解及案例
2016-05-25 19:56
281 查看
0-1背包
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602
完全背包:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1114
多重背包:http://acm.hdu.edu.cn/showproblem.php?pid=2191
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602
#include <stdio.h> #include <string.h> #include <algorithm> #define MAX 10000 using namespace std; int val[MAX]; int w[MAX]; int dp[MAX]; int main() { int t; scanf("%d",&t); while(t--) { memset(dp,0,sizeof(dp)); int n,W; scanf("%d%d",&n,&W); for(int i=0;i<n;i++) scanf("%d",&val[i]); for(int i=0;i<n;i++) scanf("%d",&w[i]); for(int i=0;i<n;i++) { for(int j=W;j>=w[i];j--) if(dp[j-w[i]]+val[i]>dp[j]) dp[j]=dp[j-w[i]]+val[i]; } printf("%d\n",dp[W]); } return 0; }
完全背包:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1114
#include <stdio.h> #include <string.h> #include <algorithm> #define MAX 10000 #define INF 0x3f3f3f3f using namespace std; int dp[MAX]; int val[MAX]; int w[MAX]; int main() { int t; scanf("%d",&t); while(t--) { memset(dp,INF,sizeof(dp)); int W,m,k; scanf("%d%d",&m,&k); W=k-m; int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d%d",&val[i],&w[i]); dp[0]=0; for(int i=0;i<n;i++) { for(int j=w[i];j<=W;j++) { dp[j]=min(dp[j],dp[j-w[i]]+val[i]); } } if(dp[W]==INF) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n",dp[W]); } return 0; }
多重背包:http://acm.hdu.edu.cn/showproblem.php?pid=2191
///2191 #include <stdio.h> #include <string.h> #include <algorithm> #define MAX 1000 using namespace std; int dp[MAX]; int val[MAX]; int w[MAX]; int num[MAX]; int main() { int t; scanf("%d",&t); while(t--) { memset(dp,0,sizeof(dp)); int W,n; scanf("%d%d",&W,&n); for(int i=0;i<n;i++) scanf("%d%d%d",&w[i],&val[i],&num[i]); for(int i=0;i<n;i++) { for(int j=0;j<num[i];j++) { for(int k=W;k>=w[i];k--) dp[k]=max(dp[k],dp[k-w[i]]+val[i]); } } printf("%d\n",dp[W]); } return 0; }
相关文章推荐
- Spring定时任务之Quartz
- HDU 4496 并查集
- kafka 数据删除策略
- java反射----根据方法名,类和对象执行对象的该方法
- 第13周阅读程序(1)虚函数
- maven打包时不带版本
- 李克强总理对戴尔说了什么,戴尔又在贵州做了什么?
- js 获取文本框中光标所在字符串索引位置
- python中多线程的使用
- python 多线程的使用
- hdu5523Game
- appium python client scroll 2 view(not in current screen)
- 各种分类算法优缺点比较
- nyoj290 动物统计加强版
- 带权值二叉树的路径最长值与路径
- Migrations中的更新语句写法,摘要
- nginx服务器安装及配置文件详解
- mysql导出表到CSV文件方法及提示错误[Err] 1290 - The MySQL server is running with the --secure-file-priv option解决办法
- hdu 5120(容斥+圆相交部分面积)
- Linux进程