这题要推几个公式,比较麻烦
m层的二叉树需要的最大宽度和高度:
(w = 2^{m - 1} * 3 - 1, m = 2, 3, ...; w = 1, m = 1)
(h = 2^{m - 2} * 3, m = 2, 3, ...; w = 1, m = 1)
#include<iostream>
using namespace std;
const int N = 2048;
char g[N][N];
int st[N][N];
int m, n;
void dfs(int m, int x, int y, int level, int cnt){
if(st[level][cnt] == 0) g[x][y] = 'o';
else return;
if(m == 1) return;
int h;
if(m >= 3) h = 3 * (1 << (m - 3)) - 1; // 上一阶二叉树的高度 - 1
else h = 1;
int nlevel = level + 1, ncnt = cnt << 1;
int x1 = x, y1 = y, x2 = x, y2 = y;
while(h --){ // 画两条边
if(st[nlevel][ncnt - 1] == 0){
++ x1, -- y1;
g[x1][y1] = '/';
}
if(st[nlevel][ncnt] == 0){
++ x2, ++ y2;
g[x2][y2] = '\';
}
}
++ x1, --y1, ++ x2, ++ y2;
// 画左右子树
if(st[nlevel][ncnt - 1] == 0) dfs(m - 1, x1, y1, nlevel, ncnt - 1);
if(st[nlevel][ncnt] == 0) dfs(m - 1, x2, y2, nlevel, ncnt);
}
int main(){
cin >> m >> n;
while(n --){
int a, b;
cin >> a >> b;
st[a][b] = 1;
}
int x = 1, y = (m == 1 ? 1 : 3 * (1 << (m - 2)));
dfs(m, x, y, 1, 1);
int h = (m == 1 ? 1 : 3 * (1 << (m - 2)));
int w = (m == 1 ? 1 : (1 << (m - 1)) * 3 - 1);
for(int i = 1; i <= h; i ++){
for(int j = 1; j <= w; j ++)
if(g[i][j]) cout << g[i][j];
else cout << ' ';
cout << endl;
}
return 0;
}