1168.FBI树
我真牛逼!算是第一个自主想出来的线段树。
我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。
FBI树是一种二叉树,它的结点类型也包括F结点,B结点和I结点三种。由一个长度为2^N的“01”串S可以构造出一棵FBI树T,递归的构造方法如下:
1) T的根结点为R,其类型与串S的类型相同;
2) 若串S的长度大于1,将串S从中间分开,分为等长的左右子串S1和S2;由左子串S1构造R的左子树T1,由右子串S2构造R的右子树T2。
现在给定一个长度为2^N的“01”串,请用上述构造方法构造出一棵FBI树,并输出它的后序遍历序列。
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
string s;int n;
const int N = 2000;
int a[N];
struct Node
{
int l, r;
char type;
}tr[N << 2];
char jud(int x) {
return x == 1 ? 'I' : 'B';
}
void pushup(int u)
{
char &now = tr[u].type;
char left = tr[u << 1].type, right = tr[u << 1 | 1].type;
if(left == right && left == 'I') now = 'I';
else if(left == right && left == 'B') now = 'B';
else now = 'F';
}
void build(int u, int l, int r)
{
if(l == r) {
tr[u] = {l, r, jud(a[l])};
cout <<tr[u].type;
return;
}
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
cout << tr[u].type;
}
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
int _pow[11];
_pow[0] = 1;
for (int i = 1; i <= 11; i ++ ) {
_pow[i] = _pow[i - 1] * 2;
}
cin >> n;
cin >> s;
for (int i = 0; i < (int)s.size(); i ++ ) {
a[i + 1] = s[i] - '0';
}
build(1, 1, _pow[n]);
cout << '\n';
// bianli(1, 1, _pow[n]);
return 0;
}
/*
3
10001011
*/