题解:P1087 [NOIP 2004 普及组] FBI 树

· · 题解

题目其实很简单,直接按照题意递归模拟就完事了。

思路

定义一个递归函数 \operatorname{solve}(l,r),其中 l,r 表示当前子串的起始和结束索引。这个函数负责构造索引在 [l,r] 里的子串对应的子树,并返回该子树的类型。

函数里面是这样的:

主函数里面调用 \operatorname{solve}(0,2^n-1) 即可(这是下标从 0 开始的代码,若下标从 1 开始,则为 \operatorname{solve}(1,2^n))。

Code

#include<bits/stdc++.h>
using namespace std;
string s;int n;
void solve(int l,int r){
    int mid=(l+r)/2,c0=0,c1=0;
    if(l!=r) solve(l,mid),solve(mid+1,r);
    for(int i=l;i<=r;i++){
        if(s[i]=='0') c0++;
        else c1++;
    }
    if(c0&&c1) cout<<'F';
    else if(c0) cout<<'B';
    else cout<<'I';
}
int main(){
    cin>>n>>s,solve(0,pow(2,n)-1);
}