[POJ1785]Binary Search Heap Construction(笛卡尔树)

Code

#include <cstdio>
#include <algorithm>
#include <cstring>
#define N 500010
using namespace std;

struct info{
	int fix,l,r,fa;
	char s[10];
	friend bool operator <(info a,info b){
		return strcmp(a.s,b.s)<0;
	}
	void clear(){l=r=fa=0;}
}T[N];
char s[233];
int n;

inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int build(int n){
	for(int i=1,j;i<=n;++i){
		for(j=i-1;T[j].fix<T[i].fix;j=T[j].fa);
		T[i].l=T[j].r;
		T[j].r=i;
		T[i].fa=j;
	}
	return T[0].r;
}

void dfs(int u){
	if(!u) return;
	printf("(");
	dfs(T[u].l);
	printf("%s/%d",T[u].s,T[u].fix);
	dfs(T[u].r);
	printf(")");
}

int main(){
	while(~scanf("%d",&n)&&n){
		for(int i=0;i<=n;T[i++].clear());
		T[0].fix=1e9;
		for(int i=1;i<=n;++i){
			scanf("%s",s);
			sscanf(s,"%[^/]/%d",T[i].s,&T[i].fix); 
		}
		sort(T+1,T+n+1);
		int rt=build(n);
		dfs(rt);puts("");
	}
	return 0;
}

 

posted @ 2018-06-27 16:24  void_f  阅读(127)  评论(0编辑  收藏  举报