数的计数【Noip2001】


【题目描述】

我们要求找出具有下列性质数的个数(包括输入的自然数n)。先输入一个自然数n(n≤1000),然后对此自然数按照如下方法进行处理:

不作任何处理;

在它的左边加上一个自然数,但该自然数不能超过原数的一半;

加上数后,继续按此规则进行处理,直到不能再加自然数为止。

【输入】

自然数n(n≤1000)。

【输出】

满足条件的数。

【输入样例】

6

【输出样例】

6

看完题目以及样例输入与输出,本人便把这6种情况列举了出来:
  1. 6
  2. 16
  3. 26
  4. 126
  5. 36
  6. 136

那么就特别简单,设一个函数Dfs,一直递归“1~参数/2”,每次递归的同时增加符合条件的数的数量即可:

【方法一】递归f(n)=1+f(1)+f(2)+···+f(n/2)
#include<cstdio> #include<iostream> #include<cmath> #include<cstring> #include<iomanip> #include<string> using namespace std; int num=0; int dfs(int n){ num++; for(int i=1;i<=n/2;i++){ dfs(i); } } int main(){ int n; cin>>n; dfs(n); cout<<num; }

提交后,情况如下:
测试点 1:    答案正确     460KB     3MS 

测试点 2:     答案正确     464KB     3MS 

测试点 3:     答案正确     456KB     2MS 

测试点 4:     答案正确     464KB     2MS 

测试点 5:     答案正确     476KB     4MS 

测试点 6:     答案正确     456KB     2MS 

测试点 7:     答案正确     464KB     2MS 

测试点 8:     答案正确     452KB     2MS 

测试点 9:     答案正确     468KB     310MS 

测试点10:     运行超时     456KB     994MS 
 
反正第9、10个点不知道已经跑到哪去了,耗时十分离谱

那么,往下看

 

【方法二】记忆化搜索

#include<iostream> #include<cstdio> #include<iomanip> #include<cstring> using namespace std; const int SB=-1438; int num[2000]; void Dfs(int n){ if(num[n]!=SB)return;//前面有结果了就不用再算 num[n]=1; for(int i=1;i<=n/2;i++){ Dfs(i); num[n]+=num[i];//统计数量,so easy } } int main(){ int n; cin>>n; for(int i=1;i<=n;i++)num[i]=SB; Dfs(n); cout<<num[n];
return 0; }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM