HDU ACM 2602
来源:互联网 发布:尚硅谷java课堂笔记 编辑:程序博客网 时间:2024/06/11 13:53
最简单的递归法:(该算法会超时。)
// 时间复杂度是 2^n
#include <iostream>
#include <cmath>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
const int MAX = 1001;
typedef struct
{
int value;
int volume;
}bone;
bone b[MAX];
int make(int i, int j) // 第i个物品, 当前剩余容量j
{
if (i <= 0)
return 0;
int r1 = 0, r2 = 0;
if (j >= b[i].volume)//第i个物品可以放入背包得到的价值
{
r1 = make(i - 1, j - b[i].volume) + b[i].value;
}
r2 = make(i - 1, j);//第i个物品没有放入背包得到的价值
if (r1 > r2)
return r1;
else
return r2;
}
int main()
{
freopen("in6.txt","r", stdin);
int t, n, v;
cin>>t;
while (t--)
{
cin>>n>>v;
for(int i = 1; i <= n; i++)
{
cin>>b[i].value;
}
for(int i = 1; i <= n; i++)
{
cin>>b[i].volume;
}
int t = make(n, v);
cout<<t<<endl;
}
}
使用动态规划。 时间复杂度是 n*v (个数 * 容量), 空间复杂度 二维矩阵(n*v) n*v 有可能大于 2^n
view plaincopy to clipboardprint?
#include <iostream>
#include <cmath>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
const int MAX = 1001;
typedef struct
{
int value;
int volume;
}bone;
bone b[MAX];
int f[MAX][MAX];
int main()
{
int t, n, v;
cin>>t;
while (t--)
{
cin>>n>>v;
for(int i = 1; i <= n; i++)
{
cin>>b[i].value;
}
for(int i = 1; i <= n; i++)
{
cin>>b[i].volume;
}
for (int i = 0; i <= v; i++)
{
f[0][i] = 0;
}
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= v; j++)
{
f[i][j] = f[i-1][j];
if (j >= b[i].volume && f[i - 1][j - b[i].volume] + b[i].value > f[i][j])
f[i][j] = f[i - 1][j - b[i].volume] + b[i].value;
}
}
cout<<f[n][v]<<endl;
}
}
简化矩阵的算法,时间复杂度同样是 n*v, 空间复杂度 一维数组(v)。
view plaincopy to clipboardprint?
#include <iostream>
#include <cmath>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
const int MAX = 1090;
typedef struct
{
int value;
int volume;
}bone;
bone b[MAX];
int dp[MAX];
int main()
{
//freopen("in6.txt","r", stdin);
int t, n, v;
cin>>t;
while (t--)
{
memset(dp, 0, sizeof(dp));
cin>>n>>v;
for(int i = 1; i <= n; i++)
{
cin>>b[i].value;
}
for(int i = 1; i <= n; i++)
{
cin>>b[i].volume;
}
for (int i = 1; i <= n; i++)
{
for (int j = v; j >= b[i].volume; j--)
{
if (dp[j] < dp[j - b[i].volume] + b[i].value)
{
dp[j] = dp[j - b[i].volume] + b[i].value;
}
}
}
cout<<dp[v]<<endl;
}
return 0;
}
- HDU ACM 2602
- hdu acm 2602 Bone Collector
- hdu-acm
- [ACM] hdu 2602 Bone Collector(01背包)
- HDU ACM 17 2602 Bone Collector
- HDU ACM 2111 Saving HDU
- hdu acm hdu 2115 Java
- ACM HDU 1000
- ACM HDU 1001
- ACM HDU 1002
- ACM HDU 1004
- HDU ACM 1198
- hdu acm 2100 Lovekey
- hdu acm 1913 Computers
- ACM HDU 1003
- ACM HDU 1009
- HDU ACM 1058
- HDU ACM 1257
- usaco_nocows
- 电子商务网站 url
- VC调试入门
- gridview detailview的区别
- 检查端口占用情况
- HDU ACM 2602
- flex右键弹出菜单(demo)
- dp学习笔记
- SSRS2008报表服务器在iis中没有虚拟目录
- c++ fast Delegate 实现代码
- 判断detailview 某列的值
- c++ builder 编写web services容易遇到的小问题
- 关于外汇储备
- [java]collection(容器类)框架图