Home PAT 1167 Cartesian Tree
Post
Cancel

PAT 1167 Cartesian Tree

Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
int n;
queue<int>q;
struct node{
    int val,left=-1,right=-1;
}in[35];
int build(int left,int right){
    if(left>right) return -1;
    int root=left,minv=0x3f3f3f3f;
    for(int i=left;i<=right;++i)
        if(minv>in[i].val){
            minv=in[i].val;
            root=i;
        }
    in[root].left=build(left,root-1);
    in[root].right=build(root+1,right);
    return root;
}
int main() {
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        scanf("%d",&in[i].val);
    int root=build(1,n);
    q.push(root);
    while(!q.empty()){
        int top=q.front();
        q.pop();
        printf("%d",in[top].val);
        if(in[top].left!=-1) q.push(in[top].left);
        if(in[top].right!=-1) q.push(in[top].right);
        if(q.empty()) printf("\n");
        else printf(" ");
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.