Login
Immutable PageDiscussionInfoAttachments

Please use a more selective search term instead of ""

Clear message
iz/競技プログラミング/Project Euler 018 Maximum path sum I

MMA

http://projecteuler.net/problem=18

動的計画法。

   1 #include <iostream>
   2 
   3 using namespace std;
   4 
   5 int data[15][15] = {
   6     {75},
   7     {95, 64},
   8     {17, 47, 82},
   9     {18, 35, 87, 10},
  10     {20, 4, 82, 47, 65},
  11     {19, 1, 23, 75, 3, 34},
  12     {88, 2, 77, 73, 7, 63, 67},
  13     {99, 65, 4, 28, 6, 16, 70, 92},
  14     {41, 41, 26, 56, 83, 40, 80, 70, 33},
  15     {41, 48, 72, 33, 47, 32, 37, 16, 94, 29},
  16     {53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14},
  17     {70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57},
  18     {91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48},
  19     {63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31},
  20     {4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23},
  21 };
  22 int dp[15][15];
  23 
  24 void debug() {
  25     for (int i = 0; i < 15; i++) {
  26         for (int j = 0; j <= i; j++) {
  27             cout << dp[i][j] << ' ';
  28         }
  29         cout << endl;
  30     }
  31 }
  32 
  33 int main() {
  34     dp[0][0] = data[0][0];
  35     for (int i = 1; i < 15; i++) {
  36         dp[i][0] = dp[i-1][0] + data[i][0];
  37         for (int j = 1; j < i; j++) {
  38             dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + data[i][j];
  39         }
  40         dp[i][i] = dp[i-1][i-1] + data[i][i];
  41     }
  42     int ans = 0;
  43     for (int i = 0; i < 15; i++) {
  44         ans = max(ans, dp[14][i]);
  45     }
  46     cout << ans << endl;
  47     return 0;
  48 }