Project Euler problem 67: find maximum cost path in 100-row triangle

前端 未结 5 1166
长情又很酷
长情又很酷 2021-02-11 06:27

In Project Euler\'s problem 67 there is a triangle given and it contains 100 rows. For e.g.

        5
      9  6
    4   6  8
  0   7  1   5

I.e. 5 + 9 + 6 + 7          


        
5条回答
  •  旧巷少年郎
    2021-02-11 07:17

    #include 
    #include 
    #include 
    #include 
    
    int main() { 
        std::vector > lines;
        lines.resize(100);
        std::ifstream input("triangle.txt");
    
        for (int i = 0; i < 100; i++) {
            for (int j = 0; j < i + 1; j++) {
                std::string number_string;
                input >> number_string;
                std::istringstream temp(number_string);
                int value = 0;
                temp >> value;
                lines[i].push_back(value);
            }
        } 
        std::vector path1;
        path1.resize(100);
        std::vector path2;
        path2.resize(100);
    
        for (int i = 0;i < 100;i++) 
            path1[i] = lines[99][i];
    
        for (int i = 98; i >= 0;i--) {  
            for(int j = 0;j < i+1;j++) {
                if(path1[j] > path1[j + 1]){
                    path2[j] = path1[j] + lines[i][j];
                } else{
                    path2[j] = path1[j + 1] + lines[i][j];
                }
            }
            for (int i = 0;i < 100;i++) 
                path1[i] = path2[i];
        }
        std::cout << path1[0] << std::endl;
    }
    

提交回复
热议问题