您的位置:首页 > 其它

HDU_3466_动规(01背包)

2015-12-20 16:19 477 查看
#include<bits/stdc++.h>
using namespace std;
const int maxn = 500 + 5;
const int maxm = 5000 + 5;
typedef struct node{
int p, q, v;
bool operator< (const node x) const {
return (q-p)<(x.q-x.p);
}
}Node;
Node c[maxn];
int F[maxn][maxm];
int main() {
int n, m;
while(cin >> n >> m) {
for(int i = 1; i <= n; i++) {
cin >> c[i].p >> c[i].q >> c[i].v;
}
sort(c+1, c+n+1);
memset(F, 0, sizeof(F));

for(int i = 1; i<= n; i++) {
for(int j = 0; j <= m; j++) {
F[i][j] = (i ==1 ? 0: F[i-1][j]);
if(j >= c[i].q) F[i][j] = max(F[i][j], F[i-1][j-c[i].p]+c[i].v);
}
}
cout << F
[m] << endl;
}
return 0;
}


使用滚动数组:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 500 + 5;
const int maxm = 5000 + 5;
typedef struct node{
int p, q, v;
bool operator< (const node x) const {
return (q-p)<(x.q-x.p);
}
}Node;
Node c[maxn];
int F[maxm];
int main() {
int n, m;
while(cin >> n >> m) {
for(int i = 1; i <= n; i++) {
cin >> c[i].p >> c[i].q >> c[i].v;
}
sort(c+1, c+n+1);
memset(F, 0, sizeof(F));
for(int i = 1; i<= n; i++) {
for(int j = m; j >= 0; j--) {
F[j] = (i ==1 ? 0: F[j]);
if(j >= c[i].q) F[j] = max(F[j], F[j-c[i].p]+c[i].v);
}
}
cout << F[m] << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: