Project Euler Homework

018.cpp

Go to the documentation of this file.
00001 
00031 #include <iostream>
00032 #include <fstream>
00033 using namespace std;
00034 
00036 const unsigned short rows=15;
00037 
00093 class triangle 
00094 {
00095         unsigned short x[rows][rows];
00096         unsigned label[rows][rows];
00097 public:
00098         triangle()
00099         {
00100                 unsigned short* p1 = &(x[0][0]);
00101                 unsigned *p2 = &(label[0][0]);
00102                 for(int i=0;i<rows*rows;i++,p1++,p2++)
00103                 { 
00104                         *p1=0;
00105                         *p2=0;
00106                 }
00107         }
00108         void push(unsigned short k)
00109         {
00110                 static unsigned short row=0;
00111                 static unsigned short col=0;
00112                 x[row][col]=k;
00113                 if(row==0)
00114                 {
00115                         row++;
00116                         label[0][0]=k;//set label
00117                         return;
00118                 }
00119                 else if(row==col)
00120                 {
00121                         row++;
00122                         col=0;
00123                         return;
00124                 }
00125                 else col++;
00126         }
00127         void label_row(unsigned short n)
00128         {
00129                 for(int k=0;k<=n-1;k++)
00130                 {
00131                         //evaluate label directly below
00132                         unsigned tmp_label = label[n-1][k]+x[n][k];
00133                         if(tmp_label > label[n][k])
00134                         label[n][k] = tmp_label;
00135                         //evalulate label at bottom right corner
00136                         label[n][k+1] = label[n-1][k]+x[n][k+1];
00137                 }
00138         }
00139         //find the max sum
00140         unsigned maxN()
00141         { 
00142         unsigned m = label[rows-1][0];
00143                 for(int k=1;k<rows;k++)
00144                 if(m<label[rows-1][k])
00145                 m = label[rows-1][k];
00146                 return m;
00147         }
00148 };
00149 void import(triangle *N)
00150 {
00151         ifstream input;
00152         input.open("018.txt");
00153         unsigned short x;
00154         for(unsigned k=1;k<=(rows+1)*rows/2;k++)
00155         {
00156                 input >> x;
00157                 N->push(x);
00158         }
00159 }
00160 int main()
00161 {
00162         triangle N;
00163         import(&N);
00164         for(unsigned short r=1;r<rows;r++)
00165         N.label_row(r);
00166         cout << N.maxN() << endl;
00167         return 0;
00168 }
 All Classes Files Functions Variables