【数据结构】递归与树Moo

描述

奶牛们迷上了一个名为“Moo”的新的单词游戏。 在玩该游戏时,奶牛们站成长长的一排,在队列中的每一头奶牛都有责任尽可能快的大声说出一个特定的字母。

在Moo游戏中,这个单词序列严格上说是无穷的,它是这样开始的: m o o m o o o m o o m o o o o m o o m o o o m o o m o o o o o

这一串最好由递归表示:令S(0)为三个字符的序列“moo” 那么更长的字符串S(k)由三部分组成,第一部分是S(k-1),第二部分是”m
o…o”(k+2个’o’),第三部分又是S(k-1)。例如:
S(0)=”m o o” S(1)=”m o o m o o o m o o”
S(2)=”m o o m o o o m o o m o o o o m o o m o o o m o o”

正如你所看到的,这个过程最终将会产生一个无穷的长字符串,并且 这个长字符串正是被玩Moo游戏的奶牛一个一个说出。

Bessie这头奶牛,自我感觉很聪明,他想要预测第N头奶牛将会说出m还是o。请你帮助他!

样例输入

11

样例输出

m

题解

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 1e9;

int a[30] = {
    
    
        3, 10, 25, 56, 119, 246, 501, 1012, 2035, 4082, 8177, 16368, 32751, 65518, 131053, 262124, 524267, 1048554,
        2097129, 4194280, 8388583, 16777190, 33554405, 67108836, 134217699, 268435426, 536870881, 1073741792
};

string mid(int x) {
    
    
    string res = "m";
    for (int i = 1; i <= x + 2; i++) res += "o";

    return res;
}

string f(int x) {
    
    

    if (x == 0) return "moo";
    return f(x - 1) + mid(x) + f(x - 1);
}

void dfs(int x, int t) {
    
    
    if (t == 0) {
    
    
        if (x == 1) puts("m");
        else puts("o");
        return;
    }

    if (x <= a[t - 1] + 3 + t) {
    
    
        if (x == a[t - 1] + 1) puts("m");
        else puts("o");
        return;
    } else {
    
    
        x -= a[t - 1] + 3 + t;
        int i;
        for (i = 0;; i++)
            if (x < a[i])
                break;
        dfs(x, i);
    }
}

int main() {
    
    
    int n;
    cin >> n;

    int i;
    for (i = 0;; i++)
        if (n < a[i])
            break;

    dfs(n, i);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_52049271/article/details/127269610