poj-2229-Sumsets(递推式)

题目链接:http://poj.org/problem?id=2229

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). 

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

从样例中很容易明白题意,找出n的所有不同个二进制组合方式

0:0;

1:1;=1

2:1 1 ;2;=2

3 :1 1 1;  2 1 ;=2

4:1 1 1 1 ;2 1 1 ;2 2 ;= 4

5:1 1 1 1 1 ;2 1 1 1 ;2 2 1;4 1;=4

6:1 1 1 1 1 1;2 1 1 1 1 ;2 2 1 1;2 2 2; 4 1 1; 4 2=6

7:1 1 1 1 1 1 1;2 1 1 1 1 1 ;2 2 1 1 1;2 2 2 1; 4 1 1 1; 4 2 1;=6

8:1 1 1 1 1 1 1 1 ;2 1 1 1 1 1 1;2 2 1 1 1 1 ;2 2 2 1 1;2 2 2 2 ;4 1 1 1 1 ;4 2 1 1 ;4 2 2;4 4;8;=10

9.....发现是8的个数,因为对于单个的1无法于其他的相互组合

类似斐波那契数列的递推式

首先写出前3项,f[0]=1,f[1]=1,f[2]=2,f[3]=3

递推式为:若n为奇数,则他就是上一个数的个数,即:f[n]=f[n-1];

若n为偶数,上一个奇数的个数加一个1就是这里以1结尾的组合情况,而以偶数部分结尾的,则是n/2*2的情况,因此得递推式:

f[n]=f[n-1]+f[n/2]

ac:

#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
//#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  
  
#define ll long long  
#define da    0x3f3f3f3f  
#define clean(a,b) memset(a,b,sizeof(a))// 水印 

int dp[1000100];

int main()
{
	int n;
	cin>>n;
	dp[0]=1;
	dp[1]=1;
	dp[2]=2;
	dp[3]=3;
	dp[4]=4;
	dp[5]=4;
	dp[6]=6;
	dp[7]=6;
	for(int i=8;i<=1000100;++i)
	{
		if(i&1)
		{
			dp[i]=dp[i-1];
		}
		else
		{
			dp[i]=(dp[i-1]+dp[i/2])%1000000000;
		}
	}
	cout<<dp[n]<<endl;
	
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/81075098