爬楼梯

题目:洛谷爬楼梯

思路很简单,主要是复杂度和高精的问题

 

 

首先,最初的递归,这效率谁用谁知道

#include <stdio.h>

long long fun(int n)
{
    if (n < 3)
        return n;
    else
        return fun(n - 1) + fun(n - 2);
}

int main()
{
    long long n = 0;
    scanf("%lld", &n);
    printf("%lld", fun(n));
    return 0;
}

 

之后,递推,效率可以,但是规定n<=5000,超出了long long 的范围,需要高精

#include <stdio.h>

long long n,num[5005];

int main()
{
    scanf("%lld", &n);
    num[1] = 1;
    num[2] = 2;
    for (int i = 3; i <= n; i++)
        num[i] = num[i - 1] + num[i - 2];
    printf("%lld", num[n]);
    return 0;
}

 

再然后,递推+高精,高精可以看看之前的这篇高精 A+B

#include <stdio.h>

long long n,num1[5002],num2[5002],len1,len2;

int main()
{
    scanf("%lld", &n);

    

    num1[0] = 1;
    num2[0] = 2;
    len1=1;
    len2=1;
    
    for (int i = 3; i <= n; i++)
    {
        if(i%2==1)//将num2加到num1上
        {
            long long len = (len1 >= len2) ? len1 : len2;
            for (int i = 0; i < len; i++)
            {
                num1[i + 1] += (num2[i] + num1[i]) / 10;
                num1[i] = (num2[i] + num1[i])% 10;
            }
            if(num1[len]==1)
                len++;
            len1=len;
        }
        else//将num1加到num2上
        {
            long long len = (len1 >= len2) ? len1 : len2;
            for (int i = 0; i < len; i++)
            {
                num2[i + 1] += (num2[i] + num1[i]) / 10;
                num2[i] = (num2[i] + num1[i])% 10;
            }
            if(num2[len]==1)
                len++;
            len2=len;
        }

    }
    if(n<3)//特解特办
        printf("%d",n);
    else if(n%2==1)
        for(int i=len1-1;i>=0;i--)
            printf("%lld",num1[i]);
    else
        for(int i=len2-1;i>=0;i--)
            printf("%lld",num2[i]);
    return 0;
}

 

posted @ 2020-07-20 10:38  _lyl  阅读(143)  评论(0编辑  收藏  举报