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)))
Source: University of Ulm Local Contest 2004
题目大意:给n个二元组,每个二元组由一个字符串和一个数字组成,中间一个/分隔。现在要求按字符串为关键字构造一颗二叉搜索树,同时按数字为关键字构造一个大堆。
题目分析:红果果的笛卡尔树。
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 50005; struct node { int dig; char cha[10]; int pa,l,r; }lcm[N]; int stack[N]; char buf[100]; int n; int cmp(struct node a,struct node b) { return strcmp(a.cha,b.cha) < 0; } int build() { int i,top,j; for(i = 0;i < n;i ++) lcm[i].l = lcm[i].r = lcm[i].pa = -1; top = -1; for(i = 0;i < n;i ++) { j = top; while(j >= 0 && lcm[stack[j]].dig < lcm[i].dig) j --; if(j != -1) { lcm[i].pa = stack[j]; lcm[stack[j]].r = i; } if(j < top) { lcm[stack[j + 1]].pa = i; lcm[i].l = stack[j + 1]; } stack[++ j] = i; top = j; } lcm[stack[0]].pa = -1; return stack[0]; } void dfs(int cur) { if(cur == -1) return; printf("("); dfs(lcm[cur].l); printf("%s/%d",lcm[cur].cha,lcm[cur].dig); dfs(lcm[cur].r); printf(")"); } int main() { int i; while(scanf("%d",&n),n) { for(i = 0;i < n;i ++) { scanf("%s",buf); sscanf(buf,"%[^/]/%d",lcm[i].cha,&lcm[i].dig); } sort(lcm,lcm + n,cmp); int root = build(); dfs(root); putchar(10); } return 0; } //280ms 1748kb