Skip to content

Commit 1ba36ed

Browse files
committed
Solved problem 1097 - Code the Tree from ZOJ
1 parent 229c62b commit 1ba36ed

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

ZOJ/1097 - Code the Tree.cpp

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
Idea:
3+
- Using recursion we can build the tree from the input.
4+
- When the tree is ready to use we can use priority queue
5+
to track the leaf nodes.
6+
- Each time we remove a node from the tree we can remove it
7+
from the `vector` of the parent node.
8+
*/
9+
10+
#include <bits/stdc++.h>
11+
12+
using namespace std;
13+
14+
char s[10001];
15+
int n, len;
16+
vector<int> sol;
17+
vector<vector<int> > g;
18+
priority_queue<int> pq;
19+
20+
int getInt(int idx) {
21+
int ret = 0;
22+
while(isdigit(s[idx]))
23+
ret *= 10, ret += (s[idx++] - '0');
24+
return ret;
25+
}
26+
27+
void build(int idx, int par) {
28+
int cur = getInt(idx);
29+
n = max(n, cur);
30+
31+
if(par != -1)
32+
g[par].push_back(cur),
33+
g[cur].push_back(par);
34+
35+
for(int i = idx, cnt = 1; i < len; ++i) {
36+
cnt += s[i] == '(';
37+
cnt -= s[i] == ')';
38+
if(cnt == 0)
39+
break;
40+
if(s[i] == '(' && cnt == 2)
41+
build(i + 1, cur);
42+
}
43+
}
44+
45+
void rmv(int from, int target) {
46+
for(int i = 0; i < g[from].size(); ++i)
47+
if(g[from][i] == target) {
48+
g[from].erase(g[from].begin() + i);
49+
break;
50+
}
51+
}
52+
53+
int main() {
54+
while(fgets(s, sizeof s, stdin)) {
55+
n = 0;
56+
len = strlen(s);
57+
g.clear();
58+
g.resize(1001);
59+
build(1, -1);
60+
61+
for(int i = 1; i <= n; ++i)
62+
if(g[i].size() == 1)
63+
pq.push(-i);
64+
65+
sol.clear();
66+
while(!pq.empty()) {
67+
int top = -pq.top();
68+
pq.pop();
69+
70+
sol.push_back(g[top][0]);
71+
rmv(g[top][0], top);
72+
if(g[g[top][0]].size() == 1)
73+
pq.push(-g[top][0]);
74+
}
75+
76+
for(int i = 0; i < int(sol.size()) - 1; ++i)
77+
printf("%s%d", i == 0 ? "" : " ", sol[i]);
78+
puts("");
79+
}
80+
81+
return 0;
82+
}

ZOJ/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Problems
2+
3+
- [1097 - Code the Tree](http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=97)

0 commit comments

Comments
 (0)