[BOJ] 4256 트리

Time Lapse :35min 39sec

4256.cpp

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#define pc(x) putchar_unlocked(x)
#define gc() getchar_unlocked()
using namespace std;
struct Node{
Node* l;
Node* r;
int val;
};
int tc, n;
int preOrder[1000];
int inOrder[1000];
int fRI(){
int N = gc(), ret = 0, flag = 1;
for(;N<'0'||N>'9';N=gc())
if(N=='-'){
flag=-1; N=gc(); break;
}
do{
ret = (ret<<3) + (ret<<1) + (N & 0b1111); N=gc();
}while('0'<=N&&N<='9');
return ret*flag;
}
inline void fWI (int n){
int N = n, rev, count = 0;
rev = N;
while ((rev % 10) == 0) { count++; rev /= 10;} //obtain the count of the number of 0s
rev = 0;
while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;} //store reverse of N in rev
while (rev != 0) { pc(rev % 10 | 0b110000); rev /= 10;}
while (count--) pc('0');
pc(' ');
}
Node* initNode() {
Node* node = new Node();
node-> val = -1;
node->l = node->r = nullptr;
return node;
}
Node* buildNode(Node* node, int pStart, int pEnd, int iStart, int iEnd) {
if(pStart > pEnd || iStart > iEnd) return nullptr;
node = initNode();
node->val = preOrder[pStart];
if(pStart == pEnd) return node;
int inOderPos;
for(inOderPos = iStart; inOderPos <= iEnd; inOderPos++)
if(inOrder[inOderPos] == preOrder[pStart])
break;
node -> l = buildNode(node->l, pStart + 1, pStart + inOderPos - iStart, iStart, inOderPos-1);
node -> r = buildNode(node->r, pStart + inOderPos - iStart + 1, pEnd, inOderPos+1, iEnd);
return node;
}
void postOrder(Node* node) {
if(node->l != nullptr) postOrder(node->l);
if(node->r != nullptr) postOrder(node->r);
fWI(node->val);
}
int main(){
tc = fRI();
while(tc--) {
n = fRI();
for(int i = 0; i < n; i++)
preOrder[i] = fRI();
for(int i = 0; i < n; i++)
inOrder[i] = fRI();
postOrder(buildNode(nullptr, 0, n - 1, 0, n - 1));
pc('\n');
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/09/07/PS/BOJ/4256/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.