动态规划_Sumsets_POJ-2229

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). 
Input
A single line with a single integer, N.
Output
The number of ways to represent N as the indicated sum. Due to the potential huge size of this number, print only last 9 digits (in base 10 representation).
Sample Input
7
Sample Output
6

对不起,是我太菜了,看到题目又没思路,接着参考大佬的博客

首先定义状态:d[i] 表示i的划分方法数

关键是这里的递推关系也就是状态转移方程:

1.所求的n为奇数,那么所求的分解结果中必含有1,因此,直接将i-1的分拆结果中添加一个1即d[i] = d[i-1]

2.所求的n为偶数,那么n的分解结果分两种情况 

  • 如果含有有1,至少有两个,则d[i-2]的每一种情况加两个1,就得到i
  • 不含有1 那么,分解因子的都是偶数,将每个分解的因子都除以2, 刚好是i/2的分解结果,并且可以与之一一对应,即d[i/2]

综上:d[i] = d[i-1] (i为奇数)

   d[i] = d[i-2] + d[i/2]  (i为偶数)

最后由于只要输出最后9个数位,别忘记模1000000000

附上AC代码:

#include<iostream>
using namespace std;
int d[1000005];
int main()
{
    int i,n;
    d[1]=1;
    d[2]=2;
    for(i=3;i<=1000000;i++) {
        if(i&1)
            d[i]=d[i-1];
        else
            d[i]=(d[i-2]+d[i/2])%1000000000;
    }
    cin>>n;
    cout<<d[n]<<endl;
    
    return 0;
}

附:

i&1用于判断是否为奇数数!如果为真,则为奇数,为假则为偶数
解释:&符号代表 按位与,1的二进制最后一位为1,其余为零。如果一个数为奇数,那么最后一位必为1,其余位必为0,所以得出结果为1。如果是偶数的话,最后一位必然为0,其余位与0与运算必为0,所以结果为0,这样就可以起到判断奇数偶数的效果

 

 

 

猜你喜欢

转载自www.cnblogs.com/wizarderror/p/10478573.html