您的位置:首页 > 其它

SDUN上部分背包问题及解析

2017-11-10 13:01 239 查看
1.首先是1033这道题

纯纯正正赤赤裸裸的01背包问题

做这种问题时,设ly是利益,设zl是限制条件,有n个东西,限制的最大条件w;

下面是思路

int b,c;
int a=[w+1];   //a[x] 表示背包容量为x 时的最大价值
for ( b=0; b<n; b++)
for ( c=w; c>=zl[i]; c--)
if(a[c]<a[c-zl[i]]+li[i])
a[c]=a[c-zl[i]]+li[i];


贴代码

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int a, b, c, d, e, f;
scanf("%d %d", &a, &b);
int t[101], j[101], s[1001] = {0};
for (c = 1; c <= b; c++)
{
scanf("%d %d", &t[c], &j[c]);
}
for (c = b; c >0; c--)
{
for (d = a; d >=t[c]; d--)
{
if (s[d] < s[d - t[c]] + j[c])
{
s[d] = s[d - t[c]] + j[c];
}
}
}
printf("%d\n", s[a]);
return 0;
}


2.完全背包问题

例如1360这道题

其实差不多思路,就是改改循环顺序;

做这种问题时,设ly是利益,设zl是限制条件,有n个东西,限制的最大条件w;

下面是思路

int b,c;
int a=[w+1];   //a[x] 表示背包容量为x 时的最大价值
for ( b=0; b<n; b++)
for ( c=zl[i]; c<=w; c++)
if(a[c]<a[c-zl[i]]+li[i])
a[c]=a[c-zl[i]]+li[i];


1360

贴代码

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int a, b, c, d, e, f;
int r[101], x[101];
while (cin >> a)
{
int m[100000] = { 0 };
for (b = 1; b <= a; b++)
{
cin >> x[b] >> r[b];
}
cin >> d;
for (c = 1; c <= a; c++)
{
for (e = r[c]; e <= d; e++)
{
if (m[e] < m[e - r[c]] + x[c])
{
m[e] = m[e - r[c]] + x[c];
}
}
}
printf("%d\n", m[d]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: