思路:纯模拟
PS.这类题我不太熟,还WA了好几次、、、
后来发现题目中一个很重要的信息没看到,就是输入的n个是一定是1-n,这样就可以简化很多、、、、、
CODE:
/*字符串模拟*/
/*AC代码:364ms*/
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <algorithm>
#define MAXN 100
using namespace std;
struct Tree
{
int v,pl,pr,ll,rr;
}Tnode[MAXN];
int N,cnt,cas;
char map[205][105];
void Add(int p,int w)//增加新节点
{
Tnode[p].ll=Tnode[p].rr=0;
Tnode[p].pl=Tnode[p].pr=-1;
Tnode[p].v=w;
return ;
}
void Insert(int p,int w)//建树
{
if(w<Tnode[p].v)
{
if(Tnode[p].pl==-1)
{
Add(cnt,w);
Tnode[p].pl=cnt++;
return;
}
else
Insert(Tnode[p].pl,w);
}
else
{
if(Tnode[p].pr==-1)
{
Add(cnt,w);
Tnode[p].pr=cnt++;
return;
}
else
Insert(Tnode[p].pr,w);
}
return;
}
void Init()
{
int i,w;
scanf("%d",&N);
scanf("%d",&w);
cnt=2;
Tnode[1].v=w;Tnode[1].pl=Tnode[1].pr=-1;
Tnode[1].ll=Tnode[1].rr=0;
for(i=2;i<=N;i++)
{
scanf("%d",&w);
Insert(1,w);
}
}
int get_posl(int p)
{
if(Tnode[p].pl==-1)
return 0;
return get_posl(Tnode[p].pl)+Tnode[p].ll;
}
int get_posr(int p)
{
if(Tnode[p].pr==-1)
return 0;
return get_posr(Tnode[p].pr)+Tnode[p].rr;
}
void Run(int p)
{
if(Tnode[p].pl==-1)
Tnode[p].ll=0;
else
{
Run(Tnode[p].pl);
Tnode[p].ll=get_posr(Tnode[p].pl)+1;
}
if(Tnode[p].pr==-1)
Tnode[p].rr=0;
else
{
Run(Tnode[p].pr);
Tnode[p].rr=get_posl(Tnode[p].pr)+1;
}
//printf("%d %d %d\n",p,Tnode[p].ll,Tnode[p].rr);
}
void Draw(int p,int x,int y)
{
int i,j;
map[x][y]='o';
if(Tnode[p].pl!=-1)//有左子树
{
for(j=1,i=y-1;j<=(Tnode[p].ll-1);j++,i--)
map[x][i]='-';
map[x][i]='+';map[x+1][i]='|';
Draw(Tnode[p].pl,x+2,i);
}
if(Tnode[p].pr!=-1)//有右子树
{
for(j=1,i=y+1;j<=(Tnode[p].rr-1);j++,i++)
map[x][i]='-';
map[x][i]='+';map[x+1][i]='|';
Draw(Tnode[p].pr,x+2,i);
}
}
void Solve()
{
int i,j,xmax,ymax;
Run(1);
for(i=0;i<205;i++)
{
for(j=0;j<100;j++)
map[i][j]=' ';
}
int pos=get_posl(1);
Draw(1,0,pos);
xmax=0;
for(i=0;i<200;i++)
{
ymax=0;
bool ok=false;
for(j=0;j<100;j++)
{
if(map[i][j]!=' ')
{
ymax=j;
ok=true;
}
}
map[i][ymax+1]='\0';
if(ok) xmax=i;
}
printf("Case #%d:\n",cas++);
for(i=0;i<=xmax;i++)
puts(map[i]);
}
int main()
{
//freopen("B.in","r",stdin);
//freopen("B2.out","w",stdout);
int T;
cas=1;
scanf("%d",&T);
while(T--)
{
Init();
Solve();
}
return 0;
}