Project Euler Homework
|
00001 #include <iostream> 00002 #include <fstream> 00003 using namespace std; 00004 00005 const unsigned short rows=100; 00006 class triangle 00007 { 00008 unsigned short x[rows][rows]; 00009 unsigned label[rows][rows]; 00010 public: 00011 triangle() 00012 { 00013 unsigned short* p1 = &(x[0][0]); 00014 unsigned *p2 = &(label[0][0]); 00015 for(int i=0;i<rows*rows;i++,p1++,p2++) 00016 { 00017 *p1=0; 00018 *p2=0; 00019 } 00020 } 00021 void push(unsigned short k) 00022 { 00023 static unsigned short row=0; 00024 static unsigned short col=0; 00025 x[row][col]=k; 00026 if(row==0) 00027 { 00028 row++; 00029 label[0][0]=k;//set label 00030 return; 00031 } 00032 else if(row==col) 00033 { 00034 row++; 00035 col=0; 00036 return; 00037 } 00038 else col++; 00039 } 00040 void label_row(unsigned short n) 00041 { 00042 for(int k=0;k<=n-1;k++) 00043 { 00044 //evaluate label directly below 00045 unsigned tmp_label = label[n-1][k]+x[n][k]; 00046 if(tmp_label > label[n][k]) 00047 label[n][k] = tmp_label; 00048 //evalulate label at bottom right corner 00049 label[n][k+1] = label[n-1][k]+x[n][k+1]; 00050 } 00051 } 00052 //find the max sum 00053 unsigned maxN() 00054 { 00055 unsigned m = label[rows-1][0]; 00056 for(int k=1;k<rows;k++) 00057 if(m<label[rows-1][k]) 00058 m = label[rows-1][k]; 00059 return m; 00060 } 00061 }; 00062 void import(triangle *N) 00063 { 00064 ifstream input; 00065 input.open("067.txt"); 00066 unsigned short x; 00067 for(unsigned k=1;k<=(rows+1)*rows/2;k++) 00068 { 00069 input >> x; 00070 N->push(x); 00071 } 00072 } 00073 int main() 00074 { 00075 triangle N; 00076 import(&N); 00077 for(unsigned short r=1;r<rows;r++) 00078 N.label_row(r); 00079 cout << N.maxN() << endl; 00080 return 0; 00081 }