ZOJ 1700 Falling Leaves 트리 구조

1321 단어
방법: 제목의 뜻을 똑똑히 보면 된다.
#include<cstdio>
#include<cstring>
const int LMT=30;
int head,cnt,tr,lev;
struct node
{
	int l,r,data;
}nod[LMT];
char ans[LMT],sec[LMT][LMT];
void init()
{
	int i;
	for(i=0;i<LMT;i++)nod[i].l=nod[i].r=-1;
	memset(ans,0,sizeof(ans));
	tr=head=0;lev=0;
	cnt=1;
}
void dfs(int pos,int pre,int is_left,int val)
{
	if(pos==-1)
	{
		if(is_left)nod[pre].l=cnt;
		else nod[pre].r=cnt;
		nod[cnt].data=val;
		cnt++;
		return;
	}
	if(val>nod[pos].data)dfs(nod[pos].r,pos,0,val);
	else dfs(nod[pos].l,pos,1,val);
}
void see(int u)
{
	if(u==-1)return;
	ans[tr]=nod[u].data+'A';tr++;
	see(nod[u].l);
	see(nod[u].r);
}
int main(void)
{
	int j,i=0;
	init();
	while(~scanf("%s",sec[lev])&&strcmp(sec[lev],"*")&&strcmp(sec[lev],"$"))
	{
		if(!strcmp(sec[lev],"$"))break;
		if(!strcmp(sec[lev],"*"))continue;
		lev++;
		while(~scanf("%s",sec[lev])&&strcmp(sec[lev],"*")&&strcmp(sec[lev],"$"))
			lev++;
		nod[head].data=sec[lev-1][0]-'A';
		for(i=lev-2;i>=0;i--)
			for(j=0;sec[i][j];j++)
			dfs(head,-1,-1,sec[i][j]-'A');
			see(head);
			printf("%s
",ans); if(!strcmp(sec[lev],"$"))break; init(); } return 0; }

좋은 웹페이지 즐겨찾기