ACM——数的计算

数的计算——(递归(超时)和非递归)

时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte
总提交:1050            测试经过:312

描述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

相关文章
相关标签/搜索