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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| #include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <map>
#define REP(i, k, n) for(int i = k; i < n; i++)
#define rep(i, n) for(int i = 0; i < n; i++)
using namespace std;
struct Tree {
int v;
Tree* left;
Tree* right;
Tree(int v) : v(v) {}
};
void f(string s, Tree* node) {
string t = "";
REP(i, 1, s.size()-1) {
t += s[i];
}
if(t == "") return;
s = t;
int root = 0, sum = 0;
string left = "";
int i = 0;
for(i = 0; i < s.size(); i++) {
left += s[i];
if(s[i] == '(') sum++;
else if(s[i] == ')') sum--;
if(sum == 0){
stringstream ss;
i += 2;
REP(j, i, s.size()) {
if(s[j] == ']') {
i++;
break;
} else {
ss << s[j];
i++;
}
}
ss >> root;
node->v = root;
break;
}
}
string right = "";
for(; i < s.size(); i++) {
right += s[i];
}
node->left = new Tree(-1);
f(left, node->left);
node->right = new Tree(-1);
f(right, node->right);
}
void merge(Tree* res, Tree* node, Tree* node2) {
res->v = node->v + node2->v;
// cout << "-------- merge:" << res->v << " " << node->v << " " << node2->v << endl;
res->left = new Tree(-1);
if(node->left != NULL && node->left->v != -1 && node2->left != NULL && node2->left->v != -1) {
merge(res->left, node->left, node2->left);
}
res->right = new Tree(-1);
if(node->right != NULL && node->right->v != -1 && node2->right != NULL && node2->right->v != -1) {
merge(res->right, node->right, node2->right);
}
}
string dfs(Tree* res) {
if(res->v == -1) {
return "()";
}
stringstream ss;
ss << res->v;
return "(" + dfs(res->left) + "[" + ss.str() + "]" + dfs(res->right) + ")";
}
int main() {
string s, t;
cin >> s >> t;
s = "(" + s + ")";
t = "(" + t + ")";
Tree *root = new Tree(-1);
f(s, root);
Tree *root2 = new Tree(-1);
f(t, root2);
Tree *res = new Tree(-1);
merge(res, root, root2);
string ret = dfs(res);
// 最後の()を取る.
REP(i, 1, ret.size()-1) {
cout << ret[i];
}
cout << endl;
return 0;
}
|