Submission
Status:
[PPPPPPPPPP]
Subtask/Task Score:
{100/100}
Score: 100
User: august
Problemset: composite tree
Language: cpp
Time: 0.003 second
Submitted On: 2026-03-15 22:55:26
#include <bits/stdc++.h>
using namespace std;
struct node {
int v;
node *l, *r;
node(int va) : v(va), l(nullptr), r(nullptr) {}
};
node* recur(string a) {
if (a == "" || a == "()") return nullptr;
int i=0;
while (i<a.size() && isdigit(a[i])) i++;
int val = stoi(a.substr(0, i));
node *root = new node(val);
int sti = i, cnt=0, enl=-1;
for (int j=sti; j<a.size(); j++) {
if (a[j] == '(') cnt++;
else if (a[j] == ')') cnt--;
if (cnt == 0) {
enl=j;
break;
}
}
int sti2 = enl+1, cnt2=0, enl2=-1;
for (int j=sti2; j<a.size(); j++) {
if (a[j] == '(') cnt2++;
else if (a[j] == ')') cnt2--;
if (cnt2 == 0) {
enl2=j;
break;
}
}
root->l = recur(a.substr(sti+1, enl-sti-1));
root->r = recur(a.substr(sti2+1, enl2-sti2-1));
return root;
}
node *merge(node *t1, node *t2) {
if (!t1 || !t2) return nullptr;
node *newnode = new node(t1->v + t2->v);
newnode->l = merge(t1->l, t2->l);
newnode->r = merge(t1->r, t2->r);
return newnode;
}
string getstr(node *t) {
if (!t) return "";
return to_string(t->v) + "(" + getstr(t->l) + ")" + "(" + getstr(t->r) + ")";
}
int main() {
cin.tie(0)->sync_with_stdio(0);
string a,b;
cin>> a>> b;
node *t1 = recur(a);
node *t2 = recur(b);
node *res = merge(t1, t2);
cout<< getstr(res);
}