Topic
描述: 一个整数总可以拆分为2的幂的和,例如:7=1+2+47=1+2+2+27=1+1+1+47=1+1+1+2+27=1+1+1+1+1+27=1+1+1+1+1+1+1总共有六种不同的拆分方式。再比如:4可以拆分成:4 = 4,4 = 1 + 1 + 1 + 1,4 = 2 + 2,4=1+1+2。用f(n)表示n的不同拆分的种数,例如f(7)=6.要求编写程序,读入n(不超过1000000),输出f(n)%1000000000。题目类别: null 难度: 初级 运行时间限制: 10Sec内存限制: 128MByte阶段: 入职前练习 输入: 每组输入包括一个整数:N(1<=N<=1000000)。输出: 对于每组数据,输出f(n)%1000000000。输出有多行,每行一个结果。输入数据如果超出范围,输出-1。样例输入: 7样例输出: 6
Ideas
当n=2k+1为奇数时,f(2k+1)=f(2k)。其实2k+1的拆分第一项肯定为1,若去掉这个1,就和2k的拆分一样了。当n=2k为偶数时,我们考虑有1和没有1的拆分。若有1,则前2项均为1,就和2k-2的拆分一样了。若没有1,则将每项除以2,就和k的拆分一样了。故有f(2k)=f(2k-2)+f(k);
Code One
/* ---------------------------------------* Date: 2015-06-30* sjf0115* title: Integer delimited * Source: Huawei on-Machine--------------------------- --------------*/#include <iostream>#include <string>#include <algorithm>#include <vector>using namespace STD;#define MAX 1000000intcount[max+1];intSplit (intN) {count[1] =1; count[2] =2; for(inti =3; I <= n;++i) {//Odd ifI2) {Count[i] = count[i-1]; }//if Else{Count[i] = (count[i-2] + count[i/2]) %1000000000; }//else}//for returnCount[n];}intMain () {intN//freopen ("C:\\users\\administrator\\desktop\\c++.txt", "R", stdin); while(Cin>>n) {if(N > Max | | n <0){return-1; }//if cout<<split (n) <<endl; }//while return 0;}
Code two
Timeout
/* ---------------------------------------* Date: 2015-06-30* sjf0115* title: Integer delimited * Source: Huawei on-Machine--------------------------- --------------*/#include <iostream>#include <string>#include <algorithm>#include <vector>using namespace STD;#define MAX 1000000intSplit (intN) {if(n = =1){return 1; }//if if(n = =2){return 2; }//if //Odd if(n%2){returnSplit (n1) %1000000000; }//if Else{returnSplit (n2) %1000000000+ Split (n/2) %1000000000; }//else}intMain () {intN//freopen ("C:\\users\\administrator\\desktop\\c++.txt", "R", stdin); while(Cin>>n) {if(N > Max) {return-1; }//if cout<<split (n) <<endl; }//while return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Huawei Machine Test exercises]14. Integer separation