- #include<iostream>
- #include<fstream>
- #include<vector>
- #include<stdlib.h>
- #include<string>
- using namespace std;
- int main() {
- const int ROWS = 15;
- vector < vector <int> >triangle; // vector of vector<ints>
- streamsize s = sizeof(int);
- fstream file;
- file.open("triangle");
- for (int i = 0; i < ROWS; i++) {
- vector<int> row;
- for (int j = 0; j < i + 1; j++) {
- /*
- * Get two characters which will form the numbers
- */
- char num[2];
- if (file.good()) {
- file.get(num, s);
- } else {
- cout << "Problem?" << endl;
- }
- int number = (int) ((num[0] - 48) * 10) + (num[1] - 48);
- cout << number << endl;
- row.push_back(number); // Insert the number linearl
- }
- triangle.push_back(row); // Place a vector into the triangle vector
- row.clear();
- /*
- * Should be at the end of the line, push the
- * internal pointer forward one to enter the
- * next line
- */
- file.seekg(1, ios::cur);
- }
- return 0;
- /*
- * Now onto the actual production of the answer!
- * Work from the bottom up, calculating the greatest
- * two number and adding them up. This will effectively
- * flatten the triangle up
- */
- for (int i = triangle.size(); i > 0; i--) {
- vector<int> row = triangle.at(i);
- for (unsigned int j = 0; j < row.size(); j++) {
- if (i > 1) {
- vector<int> above = triangle.at(i-1);
- if (j == 0) {
- /*
- * Left hand edge of the pyramid
- * Check up and right
- */
- int left = row.at(j) + above.at(j);
- int right = row.at(j) + above.at(j+1);
- // Set the valve above to the greatest answer
- if (left >= right) {
- above.at(j) = left;
- } else {
- above.at(j) = right;
- }
- } else {
- /*
- * Either in between other numbers
- * or on the right hand edge
- * Check up and left
- */
- int left = row.at(j) + above.at(j-1);
- int right = row.at(j) + above.at(j);
- if (left >= right) {
- above.at(j) = left;
- } else {
- above.at(j) = right;
- }
- }
- } else if (i == 1) {
- vector<int> above = triangle.at(i-1);
- /*
- * Program has reached row 1 (second row down)
- * Simply add the current element to the only
- * element above
- */
- int result = row.at(j) + above.at(0);
- if (result > above.at(0)) {
- above.at(0) = result;
- }
- } else {
- /*
- * Should be at the top of the triangle
- */
- cout << row.at(0) << endl;
- }
- }
- }
- }