-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.cpp
106 lines (78 loc) · 2.18 KB
/
parse.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
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
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdio>
#include <climits>
using namespace std;
// <дърво> ::= (<корен> (<празен низ>|<списък от наследници>)),
// където
// <корен> ::= <цяло число>
// <списък от наследници> ::= <дърво> | <дърво>,<списък от наследници>
// (5 ((9 ()),(1 ((4 ()),(12 ()),(42 ())))))
struct Node
{
int data;
std::vector<Node*> children;
};
// (5 ((9 ()), (1 ((4 ()), (12 ()), (42 ())))))
Node* parse(ifstream& file)
{
Node* root = nullptr;
while(!file.eof())
{
file.ignore(); // ignore '('
Node* newNode = new Node;
file >> newNode->data;
file.ignore(); // skip ' '
while(file.peek() != ')')
{
file.ignore(); // skip '('
newNode->children.push_back(parse(file));
if(file.peek() == ',')
{
file.ignore(); // skip ','
file.ignore(); // skip ' '
}
else
{
}
}
}
return root;
}
Node* parseHelper(const char* name)
{
ifstream file(name, ios::in);
parse(file);
}
// correct!
int iterate(Node* node)
{
if(node->children.empty())
return node->data;
int maxChildSum = node->children[0]->data;
for(int i = 1; i < node->children.size(); ++i)
{
Node* child = node->children[i];
maxChildSum = max(maxChildSum, iterate(child));
}
return node->data + maxChildSum;
}
int main()
{
Node* root = new Node;
root->data = 5;
for(int i = 0; i < 2; ++i)
{
root->children.push_back(new Node);
}
root->children[0]->data = 9;
root->children[1]->data = 1;
for(int i = 0; i < 3; ++i)
root->children[1]->children.push_back(new Node);
root->children[1]->children[0]->data = 4;
root->children[1]->children[1]->data = 12;
root->children[1]->children[2]->data = 42;
cout << iterate(root) << endl;
return 0;
}