描述ios
要求找出具備下列性質數的個數(包含輸入的天然數n):
先輸入一個天然數n(n<=1000),而後對此天然數按照以下方法進行處理:
1. 不做任何處理;
2. 在它的左邊加上一個天然數,但該天然數不能超過原數的一半;
3. 加上數後,繼續按此規則進行處理,直到不能再加天然數爲止.數組
輸入測試
一個天然數nspa
輸出code
一個數,表示知足條件的數的個數blog
樣例輸入遞歸
6內存
樣例輸出ci
6io
提示
樣例說明:知足條件的數是6,16,26,126,36,136
題目來源
NOIP2001 普及組
1 #include<iostream> 2 using namespace std; 3 static int sum=1; 4 static int arr[1000]={0}; 5 void fun(int& k)//遞歸方法 6 { 7 if(k==0) 8 return ; 9 for(int i=1;i<=k;i++) 10 { 11 sum++; 12 int k2=i/2; 13 fun(k2); 14 } 15 } 16 17 int f(int& k){//非遞歸方法才用全局數組保存計算結果 18 int count=0; 19 if(k==0) 20 return 0; 21 int i; 22 for(i=1;i<=k;i++){ 23 if(arr[i]!=0){ 24 count+=arr[i]; 25 } 26 else{ 27 int k2=i/2; 28 arr[i]=f(k2)+1; 29 } 30 } 31 if(count!=0) 32 return count; 33 return arr[k]; 34 } 35 int main() 36 { 37 int n1; 38 cin>>n1; 39 int k=n1/2; 40 fun(k); 41 cout<<sum<<endl; 42 cout<<f(n1)<<endl; 43 return 0; 44 }
http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1010