Read the statement of problem G for the definitions concerning trees. In the following we define the basic terminology of heaps. A heap is a tree whose internal nodes have each assigned a priority (a number) such that the priority of each internal node is less than the priority of its parent. As a consequence, the root has the greatest priority in the tree, which is one of the reasons why heaps can be used for the implementation of priority queues and for sorting.
A binary tree in which each internal node has both a label and a priority, and which is both a binary search tree with respect to the labels and a heap with respect to the priorities, is called a treap. Your task is, given a set of label-priority-pairs, with unique labels and unique priorities, to construct a treap containing this data.
Input Specification
The input contains several test cases. Every test case starts with an integer n. You may assume that 1<=n<=50000. Then follow n pairs of strings and numbers l1/p1,...,ln/pn denoting the label and priority of each node. The strings are non-empty and composed of lower-case letters, and the numbers are non-negative integers. The last test case is followed by a zero.
Output Specification
For each test case output on a single line a treap that contains the specified nodes. A treap is printed as (<left sub-treap><label>/<priority><right sub-treap>). The sub-treaps are printed recursively, and omitted if leafs.
Sample Input
7 a/7 b/6 c/5 d/4 e/3 f/2 g/1 7 a/1 b/2 c/3 d/4 e/5 f/6 g/7 7 a/3 b/6 c/4 d/7 e/2 f/5 g/1 0
Sample Output
(a/7(b/6(c/5(d/4(e/3(f/2(g/1))))))) (((((((a/1)b/2)c/3)d/4)e/5)f/6)g/7) (((a/3)b/6(c/4))d/7((e/2)f/5(g/1)))
题意:给出n个结点,有两个值key和value,要求构造一棵笛卡尔树。光看key的话,笛卡尔树是一棵二叉搜索树,每个节点的左子树的key都比它小,右子树都比它大;光看value的话,笛卡尔树有点类似堆,根节点的value是最小(或者最大)的,每个节点的value都比它的子树要小(或者大)。
思路:先按key值排序,然后一个个插入构造笛卡尔树,这里用了O(n)的算法求出了每个结点的父亲结点,然后对于每个结点,若该节点key值比父亲结点小,则为左子树,否则为右子树。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 50005;
int n;
struct node{
char s[105];
int v;
}p[maxn];
int l[maxn], r[maxn], T[maxn], st[maxn];
bool cmp(node a, node b){
return strcmp(a.s, b.s) < 0;
}
void solve(){
int k, top = -1;
memset(l, -1, sizeof(l));
memset(r, -1, sizeof(r));
for(int i = 0; i < n; i++)
{
k = top;
while(k >= 0 && p[st[k]].v < p[i].v) k--;
if(k != -1) T[i] = st[k];
if(k < top) T[st[k + 1]] = i;
st[++k] = i;
top = k;
}
T[st[0]] = -1;
for(int i = 0; i < n; i++)
{
if(T[i] == -1) continue;
if(strcmp(p[i].s, p[T[i]].s) < 0) l[T[i]] = i;
else r[T[i]] = i;
}
}
void dfs(int u){
if(u == -1) return;
printf("(");
dfs(l[u]);
printf("%s/%d", p[u].s, p[u].v);
dfs(r[u]);
printf(")");
}
int main()
{
while(scanf("%d", &n), n)
{
getchar();
for(int i = 0; i < n; i++)
{
scanf("%[^/]s", p[i].s);
scanf("/%d", &p[i].v);
getchar();
}
sort(p, p + n, cmp);
solve();
dfs(st[0]);
puts("");
}
return 0;
}