Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- #define NUM_OF_NODES 120
- #define NUM_OF_LEAVES 15
- #define NULL 0
- typedef class Node ChildNode;
- class Node {
- private:
- int data;
- ChildNode *left;
- ChildNode *right;
- public:
- Node(int node_data, ChildNode *left_node, ChildNode *right_node);
- void set_data(int dt);
- int get_data() const;
- void set_right_child(ChildNode *node);
- ChildNode* get_right_child() const;
- void set_left_child(ChildNode *node);
- ChildNode* get_left_child() const;
- };
- class TriangleGraph {
- private:
- Node root;
- int max_sum(Node root);
- public:
- TriangleGraph(Node graph_root): root(graph_root) {};
- int max_sum();
- };
- Node::Node(int node_data, ChildNode *left_node, ChildNode *right_node):
- data(node_data),
- right(right_node),
- left(left_node)
- {}
- void Node::set_data(int dt) {
- Node::data = dt;
- }
- int Node::get_data() const {
- return Node::data;
- }
- void Node::set_right_child(ChildNode *node) {
- Node::right = node;
- }
- ChildNode* Node::get_right_child() const {
- return Node::right;
- }
- void Node::set_left_child(ChildNode *node) {
- Node::left = node;
- }
- ChildNode* Node::get_left_child() const {
- return Node::left;
- }
- int TriangleGraph::max_sum (Node node) {
- if (node.get_left_child()->get_left_child() == 0) {
- return node.get_data() + max(node.get_left_child()->get_data(), node.get_right_child()->get_data());
- }
- return max(node.get_data() + max_sum(*node.get_left_child()), node.get_data() + max_sum(*node.get_right_child()));
- }
- int TriangleGraph::max_sum() {
- return TriangleGraph::max_sum(TriangleGraph::root);
- }
- int max(int a, int b) {
- return (a > b) ? a : b;
- }
- int main() {
- vector<Node> triangle_nodes;
- unsigned level = 1, nd_pos = 1;
- unsigned triangle[] = {
- 75,
- 95, 64,
- 17, 47, 82,
- 18, 35, 87, 10,
- 20, 4 , 82, 47, 65,
- 19, 1 , 23, 75, 3 , 34,
- 88, 2 , 77, 73, 7 , 63, 67,
- 99, 65, 4 , 28, 6 , 16, 70, 92,
- 41, 41, 26, 56, 83, 40, 80, 70, 33,
- 41, 48, 72, 33, 47, 32, 37, 16, 94, 29,
- 53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14,
- 70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57,
- 91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48,
- 63, 66, 4 , 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31,
- 4 , 62, 98, 27, 23, 9 , 70, 98, 73, 93, 38, 53, 60, 4 , 23
- };
- for (int i = 0; i < NUM_OF_NODES; ++i) {
- Node nd = Node(triangle[i], NULL, NULL);
- triangle_nodes.push_back(nd);
- }
- for (int i = 0; i < NUM_OF_NODES - NUM_OF_LEAVES; ++i) {
- triangle_nodes[i].set_left_child(&triangle_nodes[nd_pos++]);
- triangle_nodes[i].set_right_child(&triangle_nodes[nd_pos++]);
- if (i+1 < level*(level+1)/2)
- --nd_pos;
- else
- ++level;
- }
- TriangleGraph pyramid(triangle_nodes[0]);
- cout << pyramid.max_sum() << endl;
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement