考研机试递归和分治

分治

分:大规模问题,分解为若干个相似的小问题

治:解决边界问题

KY17 n的阶乘

描述

输入一个整数n,输出n的阶乘(每组测试用例可能包含多组数据,请注意处理)

输入描述:

一个整数n(1<=n<=20)

输出描述:

n的阶乘

示例1

输入:

3

输出:

6

由于阶乘数值太大,所以用long long 型返回值,输出格式用%lld

#include <cstdio>

long long Factorial(int n){
    if(n==1){
        return 1;//递归出口
    }
    else{
        return Factorial(n-1)*n;
    }
    
}
int main(){
    int n;
    scanf("%d",&n);
    printf("%lld\n",Factorial(n));
}

汉诺塔移动次数

#include <cstdio>

long long hanoi(int n){
    if(n==1){
        return 2;
    }
    else{
        return 3*hanoi(n-1) +2;
    }
}

int main(){
    int n;
    scanf("%d",&n);
    printf("%lld",hanoi(n));
}

KY96 Fibonacci

描述

The Fibonacci Numbers{0,1,1,2,3,5,8,13,21,34,55...} are defined by the recurrence: F0=0 F1=1 Fn=Fn-1+Fn-2,n>=2 Write a program to calculate the Fibonacci Numbers.

输入描述:

Each case contains a number n and you are expected to calculate Fn.(0<=n<=30) 。

输出描述:

For each case, print a number Fn on a separate line,which means the nth Fibonacci Number.

#include <cstdio>
int Fib(int n){
    if(n == 0){
        return 0;
    }
    else if(n == 1){
        return 1;
    }
    else{
        return (Fib(n-1)+Fib(n-2));
    }
}
int main() {
    int n;
    while(scanf("%d",&n) != EOF){
        printf("%d\n",Fib(n));
    }
    
}

KY85 二叉树

描述

如上所示,由正整数1,2,3……组成了一颗特殊二叉树。我们已知这个二叉树的最后一个结点是n。现在的问题是,结点m所在的子树中一共包括多少个结点。

比如,n = 12,m = 3那么上图中的结点13,14,15以及后面的结点都是不存在的,结点m所在子树中包括的结点有3,6,7,12,因此结点m的所在子树中共有4个结点。

输入描述:

输入数据包括多行,每行给出一组测试数据,包括两个整数m,n (1 <= m <= n <= 1000000000)。

输出描述:

对于每一组测试数据,输出一行,该行包含一个整数,给出结点m所在子树中包括的结点的数目。

示例1

输入:

3 12

0 0

输出:

4

要注意若m,n输入为0,0时,因为二叉树不存在为0的编号所以调用Tree函数,退出while循环

#include <cstdio>
int Tree(int m,int n){
    if(m > n){
        return 0;
    }
    else {
        return Tree(2*m,n)+Tree(2*m+1,n)+1;
    }
}
int main() {
    int m,n;
    while (scanf("%d%d",&m,&n) != EOF) {
        if(m==0){
            break;
        }
        printf("%d\n",Tree(m,n));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值