Binary Search Heap Construction
Time Limit:2000MS Memory Limit:30000KB
Description
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
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
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)))
3.scanf的用法,%*[ ],表示越过[ ]中的字符,%[a-z]表示读入字符串,直到遇到不是a-z中的字符为止。%[^a]表示读入字符串直到遇到字符a为止,但a并没有被读入。
题意:给出一些节点,每个节点有两个值,lable和priority(都是唯一的),要求构成一个笛卡尔树,按lable是二叉排序树,按priority是大根堆(不一定完全二叉树)。输出括号表示。
分析:先把节点按lable排序,从小到大依次插入,这样每次插入的节点就要插到排序二叉树的最右边,首先要沿着右儿子找到最右边的节点(再无右儿子),然后分两种情况,最右节点的priority和当前插入节点的priority比较,若大于则直接将当前插入节点接到其右子树。否则让当前插入节点取代最右节点位置并将原最右节点及其子树接到当前插入节点的左子树。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
char s[100];
int pri;
int l,r,fa;
}tree[50002];
bool operator < (const node &a,const node &b)
{
return strcmp(a.s,b.s)<0;
}
void insert(int i)笛卡尔树构建
{
int j=i-1;
while(tree[j].pri<tree[i].pri)
j=tree[j].fa;
tree[i].l=tree[j].r;
tree[tree[i].l].fa=i;
tree[j].r=i;
tree[i].fa=j;
}
void dfs(int x)
{
if(!x) return;
printf("(");
dfs(tree[x].l);
printf("%s/%d",tree[x].s,tree[x].pri);
dfs(tree[x].r);
printf(")");
}
int main()
{
int i,n;
while(scanf("%d",&n)&&n)
{
for(i=1;i<=n;i++)
{
scanf("%*[ ]%[^/]/%d",tree[i].s,&tree[i].pri);
tree[i].r=tree[i].l=tree[i].fa=0;
}
tree[0].l=tree[0].r=tree[0].pri=0;
tree[0].pri=0x3f3f3f3f;
sort(tree+1,tree+n+1);
for(i=1;i<=n;i++)
insert(i);
dfs(tree[0].r);
printf("\n");
}
return 0;
}