![NC16660 [NOIP2004]FBI树](https://img2022.cnblogs.com/blog/2521724/202207/2521724-20220726194541711-1623159393.png)
我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。
FBI树是一种二叉树[1],它的结点类型也包括F结点,B结点和I结点三种。由一个长度为2N的“01”串S可以构造出一棵FBI树T,递归的构造方法如下:
1) T的根结点为R,其类型与串S的类型相同;
2) 若串S的长度大于1,将串S从中间分开,分为等长的左右子串S1和S2;由左子串S1构造R的左子树T1,由右子串S2构造R的右子树T2。
现在给定一个长度为2N的“01”串,请用上述构造方法构造出一棵FBI树,并输出它的后序遍历[2]序列。
[1] 二叉树:二叉树是结点的有限集合,这个集合或为空集,或由一个根结点和两棵不相交的二叉树组成。这两棵不相交的二叉树分别称为这个根结点的左子树和右子树。
[2] 后序遍历:后序遍历是深度优先遍历二叉树的一种方法,它的递归定义是:先后序遍历左子树,再后序遍历右子树,最后访问根。
题目
- 原题地址:[NOIP2004]FBI树
- 题目编号:NC16660
- 题目类型:分治
- 时间限制:C/C++ 1秒,其他语言2秒
- 空间限制:C/C++ 131072K,其他语言262144K
1.题目大意
- 给一个长度为 2^n 的由 0 和 1 构成的序列,从根节点开始每次对半分,构成一个二叉树
- F:节点中的字符串同时包含 0 和 1
- B:节点中的字符串只包含 0
- I:节点中的字符串只包含 1
- 输出后序遍历的对应FBI序列
2.题目分析
3.题目代码
纯模拟
#include <bits/stdc++.h>
using namespace std;
typedef struct FBI{
int type;
string s;
FBI *lc,*rc;
}FBI;
int init(FBI *n){
int len = n->s.length();
if(len!=1)
{
int mid = len/2;
FBI *l = new FBI();
FBI *r = new FBI();
n->lc = l;
n->rc = r;
l->s = n->s.substr(0,mid);
r->s = n->s.substr(mid,mid);
int t = init(l) + init(r);
if(t==0)
n->type = 0;// 0 0
else if(t==1)
n->type = 4;// 0 1
else if(t==2)
n->type = 1;// 1 1
else
n->type = 4;
return n->type;
}
else
{
n->type = n->s[0] - '0';
return n->type;
}
}
void after(FBI *n){
if(n->lc)
{
after(n->lc);
after(n->rc);
}
if(n->type==0)
cout << 'B';
else if(n->type==1)
cout << 'I';
else if(n->type==4)
cout << 'F';
}
int main() {
int n;
FBI *head = new FBI();
cin >> n;
cin >> head->s;
init(head);
after(head);
}
直接求解
#include <bits/stdc++.h>
using namespace std;
char FBI(string s) {
if (s.length() > 1) {
cout << FBI(s.substr(0, s.length() / 2));
cout << FBI(s.substr(s.length() / 2, s.length() / 2));
}
if (s == string(s.length(), '0')) return 'B';
if (s == string(s.length(), '1')) return 'I';
return 'F';
}
int main() {
int n;
string s;
cin >> n >> s;
cout << FBI(s) << endl;
return 0;
}