有不会的点欢迎评论
1.志乃卖瓜
#include <iostream>
#include <algorithm>
using namespace std;
int w[100010], dp[3333][3333];
int n, m;
const int mod = 1e9 + 7;
signed main() {
cin >> n >> m; if (n == 0) {
cout << 0;
return 0;
}
for (int i = 1; i <= n; ++i) cin >> w[i];
dp[1][w[1]] = dp[1][w[1]/2] = dp[1][0] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
dp[i][j] = (dp[i][j] + dp[i - 1][j]) % mod;
if(j >= w[i])dp[i][j] = (dp[i][j] + dp[i - 1][j - w[i]]) % mod;
if(j >= w[i] / 2)dp[i][j] = (dp[i][j] + dp[i - 1][j - w[i] / 2]) % mod;
}
}
for (int i = 1; i <= m; ++i) cout << dp[n][i] << ' ' ;
return 0;
}
滚动dp写法
#include<bits/stdc++.h>
using
namespace
std;
const
int
MAXN=1005;
int
n,m,x;
const
long
long
mod=1e9+7;
long
long
dp[MAXN];
int
main()
{
dp[0]=1;
scanf
(
"%d %d"
,&n,&m);
for
(
int
i=1;i<=n;++i)
{
scanf
(
"%d"
,&x);
for
(
int
i=m;i;--i)
{
if
(i>=x/2)dp[i]+=dp[i-x/2];
if
(i>=x)dp[i]+=dp[i-x];
while
(dp[i]>=mod)dp[i]-=mod;
}
}
for
(
int
i=1;i<=m;++i)
{
printf
(
"%lld%c"
,dp[i],
" \n"
[i==m]);
}
return
0;
}
2.魔法卡片
#include<iostream>
using
namespace
std;
typedef
long
long
ll;
ll dp[10000][10000];
ll a[10000],b[10000];
int
main(){
int
n,m;
cin>>n>>m;
for
(
int
i=1;i<=n;i++){
cin>>a[i]>>b[i];
}
for
(
int
i=0;i<=n;i++){
for
(
int
l=0;l<=m;l++)
dp[i][l]=-1e16;
}
dp[0][0]=0;
for
(
int
i=1;i<=n;i++){
for
(
int
l=0;l<=m;l++){
if
(m<a[i])
dp[i][l]=dp[i-1][l];
dp[i][l]=max(dp[i-1][l],dp[i-1][(l-a[i]%m+m)%m]+b[i]);
}
}
if
(dp[n][0]<=0) cout<<
"-1"
;
else
cout<<dp[n][0];
}