树的转换
总时间限制:
5000ms
内存限制:
65536kB
描述
我们都知道用“左儿子右兄弟”的方法可以将一棵一般的树转换为二叉树,如:
0 0 / | \ / 1 2 3 ===> 1 / \ \ 4 5 2 / \ 4 3 \ 5
现在请你将一些一般的树用这种方法转换为二叉树,并输出转换前和转换后树的高度。
输入
输入包括多行,最后一行以一个#表示结束。
每行是一个由“u”和“d”组成的字符串,表示一棵树的深度优先搜索信息。比如,dudduduudu可以用来表示上文中的左树,因为搜索过程为:0 Down to 1 Up to 0 Down to 2 Down to 4 Up to 2 Down to 5 Up to 2 Up to 0 Down to 3 Up to 0。
你可以认为每棵树的结点数至少为2,并且不超过10000。
输出
对于每棵树,按如下格式输出转换前和转换后树的高度:
Tree t: h1 => h2
其中t是树的编号(从1开始),h1是转换前树的高度,h2是转换后树的高度。
样例输入
dudduduudu ddddduuuuu dddduduuuu dddduuduuu #
样例输出
Tree 1: 2 => 4 Tree 2: 5 => 5 Tree 3: 4 => 5 Tree 4: 4 => 4
AC代码1
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[100001];
int cnt=0;
while(1)
{
cnt++;
gets(s);
if(s[0]=='#')break;
int l=strlen(s);
int h,maxh;
int a[100001]={0};
int sum=0,maxsum=0;
h=0;maxh=0;
for(int i=0;i<=l-1;i++)
{
if(s[i]=='d')
{
h++;
a[h]++;
sum=sum+a[h];
a[h+1]=0;
if(sum>maxsum)
{
maxsum=sum;
}
if(h>maxh)
{
maxh=h;
}
}
else
{
sum=sum-a[h];
h--;
}
}
printf("Tree %d: %d => %d\n",cnt,maxh,maxsum);
memset(s,0,sizeof(s));
}
}
下面是直接建树dfs结果在百炼AC在数算班上TLE的屑代码
#include<bits/stdc++.h>
using namespace std;
typedef struct node tree;
typedef tree* pnode;
struct node
{
int n;
int id;
pnode q[10001];
pnode dad;
};
//pnode head;
int height,maxheight;
void dfs(pnode h)
{
pnode p;
if(h->n==0)
{
if(maxheight<height)
{
maxheight=height;
}
return;
}
for(int i=1;i<=h->n;i++)
{
height=height+i;
dfs(h->q[i]);
height=height-i;
}
}
void fr(pnode h)
{
if(h->n==0)
{
free(h);
return;
}
for(int i=1;i<=h->n;i++)
{
fr(h->q[i]);
}
free(h);
}
int main()
{
char s[100000];
int cnt=0;
//memset(s,0,sizeof(s));
while(1)
{
//printf("1");
gets(s);
if(s[0]=='#')
{
break;
}
cnt++;
int l=strlen(s);
int h,maxh;
pnode p,head;
head=(pnode)malloc(sizeof(tree));
p=head;
head->n=0;
head->id=0;
head->dad=NULL;
h=0;maxh=0; height=0;maxheight=0;
for(int i=0;i<=l-1;i++)
{
if(s[i]=='d')
{
pnode temp;
temp=(pnode)malloc(sizeof(tree));
temp->n=0;
p->n++;
p->q[p->n]=temp;
temp->dad=p;
temp->id=p->id+p->n;
if(temp->id>maxheight)
{
maxheight=temp->id ;
}
p=temp;
h++;
if(h>maxh)
{
maxh=h;
}
}
else
{
p=p->dad;
h--;
}
}
//dfs(head);
printf("Tree %d: %d => %d\n",cnt,maxh,maxheight);
memset(s,0,sizeof(s));
fr(head);
}
}