先上题目:
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/pndenoting 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)))
题意:好像就是叫你求Treap树。给出字符串和优先值,要求建一棵二叉树,根据字符串排序,然后父亲的优先值要比儿子大。然后先序遍历输出这个Treap树。
最水的方法就是直接先按优先值排序,然后逐个逐个元素添加。但是这样做绝对超时。
可以通过的第一种方法:首先先按字符串大小排个序,然后从小到大扫描一次,求出每个元素左边优先值比它大的最近的元素的位置在哪。同理从大到小扫描,求出每个元素右边优先值比它大的最近的元素的位置在哪。(没错,就是单调栈),然后在每个扫描到的最近位置加一个对应的括号(左括号或者右括号)就是答案了。总的时间复杂度O(nlogn)。
第二种方法是用RMQ求出区间优先值的最大值的下标,然后每次找出区间最大值作为根构造两边的子树就可以了。总的时间复杂度也是O(nlogn)。
比赛的时候用的方法是第二种,但是当时求对数的时候底数不是2,所以提交一直都是段错误。
上代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define MAX 50002 5 #define INF 0x3f3f3f3f 6 using namespace std; 7 8 typedef struct node{ 9 char l[200]; 10 int p; 11 12 bool operator < (const node& o)const{ 13 return strcmp(l,o.l)<0; 14 } 15 }node; 16 17 int n; 18 node e[MAX]; 19 char ch[MAX]; 20 int l[MAX],r[MAX]; 21 int al[MAX],ar[MAX]; 22 23 inline void put(char c,int ti){ 24 for(int i=0;i<ti;i++) putchar(c); 25 } 26 27 int main() 28 { 29 char* sp; 30 //freopen("data.txt","r",stdin); 31 while(scanf("%d",&n),n){ 32 for(int i=1;i<=n;i++){ 33 scanf("%s",ch); 34 sp=strchr(ch,'/'); 35 *sp='