本題實現的是treap的結構,從key的角度來看是一個BST,從priority的角度來講是一個heap,如果用treap的定義,每次插入進行旋轉,這道題會超時,因此先針對key進行排序,排序好之後再按照順序插入到treap中。
這裏一個小技巧是,將treap[0]的位置的priority置爲INT_MAX,這樣保證無論treap結構如何變化,根節點總是treap[0]的右孩子,防止根節點變化帶來的麻煩
#include <iostream>
#include <cstdio>
#include <limits.h>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxn 150
#define maxl 50050
struct node{
char str[maxn];
int pa,ls,rs;
int pri;
};
bool operator <(node a, node b){
return strcmp(a.str,b.str)<0;
}
node treap[maxl]={0};
void insert(int i){
int j = i-1;
while(treap[j].pri < treap[i].pri){
j = treap[j].pa;
}
treap[i].ls = treap[j].rs;
treap[j].rs = i;
treap[i].pa = j;
}
void dscan(int k){
if(!k)
return;
printf("(");
dscan(treap[k].ls);
printf("%s/%d",treap[k].str,treap[k].pri);
dscan(treap[k].rs);
printf(")");
}
int main(){
int n;
while(scanf("%d",&n)){
if(!n)
break;
getchar();
memset(treap,0,sizeof(treap));
for(int i=1;i<=n;++i){
cin.getline(treap[i].str,maxn,'/');
scanf("%d",&treap[i].pri);
getchar();
}
treap[0].pri = INT_MAX;
sort(treap+1,treap+n+1);
for(int i=1;i<=n;++i){
insert(i);
}
dscan(treap[0].rs);
printf("\n");
}
return 0;
}