poj 2229 (dp 完全背包相似问题)

本文探讨了一道有趣的算法题,即给定一个整数N,求由2的幂次方组成的数集,其元素之和等于N的所有可能组合的数量。文章通过动态规划的方法给出了详细的解决方案,并提供了参考代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Farmer John commanded his cows to search for different sets of numbers that sum to a given number. The cows use only numbers that are an integer power of 2. Here are the possible sets of numbers that sum to 7: 

1) 1+1+1+1+1+1+1 
2) 1+1+1+1+1+2 
3) 1+1+1+2+2 
4) 1+1+1+4 
5) 1+2+2+2 
6) 1+2+4 

Help FJ count all possible representations for a given integer N (1 <= N <= 1,000,000). 

题目大意: 给你一个数n,问你使用integer power of 2,(1, 2 ,4 8...)   这些数有多少种方法满足之和为n;


题目分析: d[i][v]  表示前i物品之和为v的最多数量,  有状态转移方程 d[i][v]  = sum(d[i-1][v-k*c[i]] |   0 < k*c[i] <=v)

                      利用完全背包O(vn)优化的思想, 这里思想是相同的,则d[v] += d[v-c[i]] 


参考代码:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = (int)1e6+10;
int n, d[maxn], c[30], m;
int Mod = (int)1e9;

void init(){
    c[1] = 1;
    for(int i = 2; ; ++i){
        c[i] = c[i-1]*2;
        if(c[i] >= maxn){
            m = i; break;
        }
    }
}

int main()
{
    init();
    while(~scanf("%d", &n)){
        memset(d, 0, sizeof(d));
        d[0] = 1;
        for(int i = 1; i < m; ++i){
            if(c[i] > n) break;
            for(int v = c[i]; v <= n; ++v){
                d[v] += d[v-c[i]];
                if(d[v] > Mod) d[v]%=Mod;
            }
        }
        printf("%d\n", d[n]);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值