LG1028 数的求解(记录)

来源:互联网 发布:专业网络公关 编辑:程序博客网 时间:2024/06/06 07:13

题目描述

我们要求找出具有下列性质数的个数(包含输入的自然数n):

先输入一个自然数n(n<=1000),然后对此自然数按照如下方法进行处理:

1.不作任何处理;

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

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

输入输出格式

输入格式:
一个自然数n(n<=1000)

输出格式:
一个整数,表示具有该性质数的个数。

Input Sample:6

Output Sample : 6

Thinking:

刚开始就暴力求解,纯递归,后来只过了5个数据,RE了15 个。然后我就GG了。后来看了题解,才知道要用递归,自己思考的太少了,too young too simple。打开博客才发现11月我一道题都没写,因为我看白书到高级篇已经看不下去了,然后拐回来复习,后来在洛谷发现有试炼场,就做了新手村。

递归代码

#include<iostream>#include<cstdio>using namespace std;int n;int sum = 1;void solve(int nn) {    if (nn == 1) {        return;    }    else {        for (int i = 1; i <= nn / 2; i++) {            sum++;            solve(i);        }    }}int main() {    scanf("%d", &n);    solve(n);    printf("%d\n", sum);    return 0;}

递推代码

可以发现 2n 和 2n+1的结果是一样的因为2n/2 = n, (2n+1)/2 = n+1/2 = n。
然后,当 n = 1 或者 0 时,显然结果为1。
观察,re[n] = re[n-1]; n%2 == 1
re[n] = re[n-1] + re[n/2]; n%2 == 0

#include<cstdio>#include<string>#include<iostream>using namespace std;int n, re[1006];int main(){    scanf("%d", &n);    re[0] = re[1] = 1;    for(int i = 2; i <= n; i++){        if(i%2 == 0){            re[i] = re[i-1] + re[i/2];        }else{            re[i] = re[i-1];        }    }    printf("%d\n", re[n]);    return 0;}