第三题是二位花费的背包问题,每件物品要花费0和1各x和y个,总共有n个0和m个1,问每件物品最多取一次,最多可以取多少物品,递归公式为a[j][k]
=
max(a[j-thing[i].x][k-thing[i].y,a[j][k]),其中thing[i].x为第i件物品消耗多少个x,thing[i].y为第i件物品消耗1的个数。
我的代码:(100%通过)
#include
<iostream>
using
namespace
std
;
struct
thing {
int
x;
//
需要
0
的个数
int
y;
//
需要
1
的个数
thing(){
x
=
0
;
y
=
0
;
}
};
int
maxx(
int
x,
int
y)
{
if
(x<y)
return
y;
return
x;
}
int
main(
int
argc,
const
char
* argv[]) {
int
x,n,m;
cin
>>x>>n>>m;
string
s[
55
];
thing
th[
55
];
int
a[
555
][
555
];
for
(
int
i=
0
;i<x;i++)
cin
>>s[i];
for
(
int
i=
0
;i<x;i++)
for
(
int
j=
0
;j<s[i].
length
();j++)
{
if
(s[i][
j
] ==
'0'
)
th[i].
x
++;
else
if
(s[i][
j
] ==
'1'
)
th[i].
y
++;
}
for
(
int
i=
0
;i<=n;i++)
for
(
int
j=
0
; j<=m;j++)
a[i][j]=
0
;
//
边界
int
ans=
0
;
for
(
int
i=
1
;i<=x;i++)
for
(
int
j=n;j>=th[i-
1
].
x
;j--)
for
(
int
k=m;k>=th[i-
1
].
y
;k--)
{
a[j][k]=
maxx
(a[j][k],a[j-th[i-
1
].
x
][k-th[i-
1
].
y
]+
1
);
if
(a[j][k]>ans)
ans=a[j][k];
}
cout
<<ans<<
endl
;
return
0
;
}