标准打印一棵树

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<queue>
 6 #include<cstring>
 7 #define PAU putchar(' ')
 8 #define ENT putchar('\n')
 9 #define CH for(int d=0;d<2;d++)if(ch[d])
10 #define lson x->ch[0],L,M
11 #define rson x->ch[1],M+1,R
12 using namespace std;
13 const int maxn=500000+10,maxnode=1000000+10,inf=-1u>>1;
14 struct node{
15     node*ch[2];int pos,x;node(){x=-inf;}
16     void update(){
17         x=-inf;CH{if(ch[d]->x>x)x=ch[d]->x,pos=ch[d]->pos;}return;
18     }
19 }seg[maxnode],*nodecnt=seg,*root;int n,A[maxn];
20 queue<node*>Q[10000];
21 void build(node*&x=root,int L=1,int R=n){
22     x=nodecnt++;int M=L+R>>1;if(L==R)x->pos=L,x->x=A[M];
23     else build(lson),build(rson),x->update();return;
24 }
25 int ql,qr,_pos,_v;//1
26 void query(node*x=root,int L=1,int R=n){
27     if(ql<=L&&R<=qr){
28         if(_v<x->x)_v=x->x,_pos=x->pos;
29     }else{int M=L+R>>1;
30         if(ql<=M)query(lson);if(qr>M)query(rson);
31     }return;
32 }
33 void dfs(node*x,int d){
34     if(!x)return;Q[d].push(x);
35     dfs(x->ch[0],d+1);dfs(x->ch[1],d+1);return;
36 }
37 void prints(){
38     dfs(root,0);
39     for(int i=0;!Q[i].empty();i++){
40         while(!Q[i].empty()){
41             printf("(%d %d) ",Q[i].front()->pos,Q[i].front()->x);
42             Q[i].pop();
43         }ENT;
44     }return;
45 }
46 inline int read(){
47     int x=0,sig=1;char ch=getchar();
48     for(;!isdigit(ch);ch=getchar())if(ch=='-')sig=0;
49     for(;isdigit(ch);ch=getchar())x=10*x+ch-'0';
50     return sig?x:-x;
51 }
52 inline void write(int x){
53     if(x==0){putchar('0');return;}if(x<0)putchar('-'),x=-x;
54     int len=0,buf[15];while(x)buf[len++]=x%10,x/=10;
55     for(int i=len-1;i>=0;i--)putchar(buf[i]+'0');return;
56 }
57 void init(){
58     n=read();
59     for(int i=1;i<=n;i++)A[i]=read();
60     build();
61     /*while(true){
62         _v=-inf;ql=read();qr=read();query();write(_pos);ENT;
63     }*/
64     prints();
65     return;
66 }
67 void work(){
68     return;
69 }
70 void print(){
71     return;
72 }
73 int main(){init();work();print();return 0;}
74 /*
75 8
76 5 2 4 3 7 1 8 5
77 1 3
78 */

what can I say?just good!

posted @ 2015-08-05 10:02  AI_Believer  阅读(236)  评论(0编辑  收藏  举报