I wrote my solution to Project Euler #18 and #67 in C++ (which I'm relatively new to), and was just wondering what everyone else thinks of it. It executes in 3-4ms and works flawlessly (even for triangles not given by the website). But I'm not a professional programmer or anything, so I wouldn't know if it's necessarily good or not. Anyone have any potential improvements?
The website's instructions:
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3 7 4 2 4 6 8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one hundred rows.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
#include <vector>
int main()
{
using namespace std;
clock_t starttim = clock();
//prog
vector<vector<int>> lines;
ifstream istrm("triangle.txt");
string line;
while (getline(istrm, line))
{
int num;
stringstream ss(line);
vector<int> curvec;
while (ss >> num)
{
curvec.push_back(num);
}
lines.push_back(curvec);
}
for (int currow = lines.size() - 1; currow >= 0; currow--)
{
if (currow != 0)
{
for (int curidx = 0; curidx <= lines[currow].size() - 2; curidx++)
{
int num1 = lines[currow][curidx];
int num2 = lines[currow][curidx + 1];
int greater = (num1 > num2 ? num1 : num2);
lines[currow - 1][curidx] += greater;
}
}
else cout << lines[0][0] << endl;
}
//endprog
cout << "Execution time - " << (((clock() - starttim) / (double)CLOCKS_PER_SEC) * 1000) << "ms." << endl;
system("PAUSE");
return 0;
}