- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem018.cpp
More file actions
Latest commit
38 lines (36 loc) · 936 Bytes
/
Copy pathproblem018.cpp
File metadata and controls
38 lines (36 loc) · 936 Bytes
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
#include<cmath>
#include<cstdlib>
#include<fstream>
#include<iostream>
#include<vector>
intmaximumPathSum(std::vector<int> triangle)
{
int height = sqrt(2 * triangle.size());
for (int i = height - 2; i >= 0; --i) {
int start = i * (i + 1) / 2;
int end = start + i;
for (int j = start; j <= end; ++j) {
triangle[j] += std::max(triangle[j + i + 1], triangle[j + i + 2]);
}
}
return triangle[0];
}
intmain(int argc, char* argv[])
{
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " <input>\n";
return0;
}
std::ifstream file(argv[1]);
if (!file.is_open()) {
std::cerr << "Cannot open " << argv[1] << '\n';
returnEXIT_FAILURE;
}
std::vector<int> triangle;
int x;
while (file >> x) {
triangle.push_back(x);
}
std::cout << "Answer: " << maximumPathSum(triangle) << '\n';
return0;
}