[Data Structure] Recursion and Tree Moo

describe

The cows are obsessed with a new word game called "Moo." To play the game, cows stand in a long line, and each cow in the line has the responsibility of saying a specific letter out loud as quickly as possible.

In the game Moo, this word sequence is technically infinite, and it starts like this: moomooomoomoooomoomoo omoomooooo

This string is best represented recursively: let S(0) be the sequence of three characters "moo" Then the longer string S(k) consists of three parts, the first part is S(k-1), the second part The first part is "m
o...o" (k+2 'o'), and the third part is S(k-1). For example:
S(0)=”moo” S(1)=”moomooomoo”
S(2)=”moomooomoomoooomoomoo omoo”

As you can see, this process will eventually produce an infinitely long string, and this long string is spoken one by one by the cows playing the Moo game.

Bessie, the cow, feels very smart. He wants to predict whether the Nth cow will say m or o. Please help him!

Sample input

11

Sample output

m

answer

#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;
}

Guess you like

Origin blog.csdn.net/weixin_52049271/article/details/127269610