蓝桥杯备赛:动态规划(01背包、完全背包)+例题

题目练习:

  1. Acwing.整数拆分(蓝桥杯每日一题)

#include<bits/stdc++.h>
using namespace std;
const int MOD=1e9;
int n;
int f[1000005];
int main(){
    f[0]=1;
    cin>>n;
    for(int i=1;i<=n;i*=2){//当前物品所用的体积 
        for(int j=i;j<=n;j++){
            f[j]=(f[j]+f[j-i])%MOD;
        }
    }
    cout<<f[n];
} 
  1. 数字组合(算法竞赛进阶指南)

//01背包
#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[1005],f[10005];//f[j] (从前i个数选) 和为j的方案数有多少个 
int main(){
    f[0]=1;//注意初值位1
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=n;i++){
        for(int j=m;j>=a[i];j--){
            f[j]=f[j]+f[j-a[i]]; 
        }
    }
    
    cout<<f[m];
} 
  1. 自然数拆分(算法竞赛进阶指南)

//完全背包
#include<bits/stdc++.h>
using namespace std;
const long long modd=2147483648;
int n;
long long f[4005];//f[j] (从前i个数选) 和为j的方案数有多少个 //注意开long long ,否则会WA
int main(){
    f[0]=1;
    cin>>n;
    for(int i=1;i<n;i++){
        for(int j=i;j<=n;j++){
            f[j]=(f[j]+f[j-i])%modd; 
        }
    }
    
    cout<<f[n];
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值