forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1097Code the Tree.cpp
More file actions
140 lines (130 loc) · 2.46 KB
/
1097Code the Tree.cpp
File metadata and controls
140 lines (130 loc) · 2.46 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
zju 1097 Code the Tree
00:00.00 440k
2004.08.19 by adai
*/
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#ifdef WIN32
#define for if(0); else for
#endif
#define MAXN 1000
int father[MAXN];
int leaf[MAXN]; //represent how many leaves this node has
int mn; //maximum number
int total; //equal mn
int root; //the root of the tree
void mm(char input[MAXN], int start, int end, int num) {
int nn = 0;
int i;
for (i = start; i <= end; i ++) {
if (input[i] == ' ') break;
nn = nn * 10 + input[i] - '0';
}
leaf[nn] = 0;
total ++;
leaf[num] ++;
father[nn] = num;
int tt = 0;
int begin = i + 1;
for (i ++; i <= end; i ++) {
if (input[i] == '(') tt ++;
if (input[i] == ')') {
tt --;
if (tt == 0) {
mm(input, begin + 1, i - 1, nn);
begin = i + 2;
}
}
}
}
int main () {
char input[MAXN];
int i;
while (1) {
cin.getline(input, MAXN, '\n');
if (cin.fail()) break;
memset(father, 0, sizeof(father));
memset(leaf, -1, sizeof(leaf));
int len = strlen(input);
int num = 0;
mn = total = 0;
for (i = 1; i < len - 1; i ++) {
if (input[i] == ' ') break;
num = num * 10 + input[i] - '0';
}
root = num;
total ++;
leaf[num] = 0;
int tt = 0;
int start = i + 1;
for (i ++; i < len - 1; i ++) {
if (input[i] == '(') tt ++;
if (input[i] == ')') {
tt --;
if (tt == 0) {
mm(input, start + 1, i - 1, num);
start = i + 2;
}
}
}
if (total == 1) {
printf("\n");
continue;
}
if (total == 2) {
printf("2\n");
continue;
}
mn = total;
if (leaf[root] == 1) {
leaf[root] = 0;
for (int ii = 1; ii <= mn; ii ++) {
if (father[ii] == root && leaf[ii] != -1) {
leaf[ii] ++;
father[root] = ii;
father[ii] = 0;
root = ii;
break;
}
}
}
int first = 1;
while (1) {
for (i = 1; i <= mn; i ++) {
if (leaf[i] == 0) {
leaf[i] = -1;
if (first) first = 0;
else printf(" ");
printf("%d", father[i]);
leaf[father[i]] --;
total --;
if (leaf[root] == 1) {
leaf[root] = 0;
for (int ii = 1; ii <= mn; ii ++) {
if (father[ii] == root && leaf[ii] != -1) {
leaf[ii] ++;
father[root] = ii;
father[ii] = 0;
root = ii;
break;
}
}
}
break;
}
}
if (total == 2) break;
}
printf(" %d\n", mn);
}
return 0;
}