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

· · 题解

题意简单易懂,递归模拟即可。

00 前置知识

  1. 读入 01 字符串 s。
  2. 递归建树:先确定根节点类型,再依次递归左、右子树。
  3. 后序输出。

超级详细的注释,请看代码。

02 代码

注释版

#include<bits/stdc++.h>
using namespace std;
string s;//字符串
int n;//长度:2^n
char a[11000];//树
char types(string q){//判断字符串的类型
    if(q.find('0')==-1)//全 1 串称为 I 串
        return 'I';
    if(q.find('1')==-1)//全 0 串称为 B 串
        return 'B';
    return 'F';//既含 0 又含 1 的串则称为 F 串
}
void build_fbi(string q,int root){
    if(root>=(1<<n+1)||q=="")return;//递归边界条件
    a[root]=types(q);//处理根节点
    build_fbi(q.substr(0,q.size()/2),root*2);//递归构造左子树
    build_fbi(q.substr(q.size()/2),root*2+1);//递归构造右子树
}
void bout(int k){//后序输出
    if(a[k]=='0')return;//边界
    bout(k*2);//左
    bout(k*2+1);//右
    cout<<a[k];//中
}
int main(){
    memset(a,'0',sizeof a);//初始化 不然 RE
    cin>>n>>s;//输入
    build_fbi(s,1);//建树
    bout(1);//输出
    return 0;
}

无注释版

#include<bits/stdc++.h>
using namespace std;
string s;
int n,len;
char a[11000];
char types(string q){
    if(q.find('0')==-1)
        return 'I';
    if(q.find('1')==-1)
        return 'B';
    return 'F';
}
void build_fbi(string q,int root){
    if(root>=(1<<n+1)||q=="")return;
    a[root]=types(q);
    build_fbi(q.substr(0,q.size()/2),root*2);
    build_fbi(q.substr(q.size()/2),root*2+1);
}
void bout(int k){
    if(a[k]=='0')return;
    bout(k*2);
    bout(k*2+1);
    cout<<a[k];
}
int main(){
    memset(a,'0',sizeof a);
    cin>>n>>s;
    build_fbi(s,1);
    bout(1);
    return 0;
}

评测记录

又是写大水题题解的一天。