poj1163 The Triangle ——DP入门题

May 20, 2013
POJ DP

题目链接:http://poj.org/problem?id=1163 题目思路:   从三角形的底部开始考虑


#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAX = 100;
int a[MAX][MAX], dp[MAX][MAX];
int main(void) {
  //freopen("1163.in", "r", stdin);
  int n,i,j; scanf("%d",&n);
  for (i = 0; i < n; ++i) {
    for (j = 0; j < i+1; ++j) {
      scanf("%d", &a[i][j]);
    }
  }
  memset(dp, 0, sizeof(dp));
  for (i = 0; i < n; ++i) dp[n-1][i] = a[n-1][i];
  for (i = n - 2; i >= 0; --i) {
    for (j = 0; j < n - 1; ++j) {
      dp[i][j] = max(dp[i+1][j], dp[i+1][j+1]) + a[i][j];
    }
  }
  printf("%d\n", dp[0][0]);
  return 0;
}

还是从最简单的开始做起吧 另外一种写法:  


#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAX = 100;
int a[MAX][MAX], dp[MAX][MAX], n;
int f(int i, int j) {
  if (dp[i][j] >= 0) return dp[i][j];
  else {
    if (i == n-1) dp[i][j] = a[i][j];
    else dp[i][j] = a[i][j] + max(dp[i+1][j], dp[i+1][j+1]);
    return dp[i][j];
  }
}
int main(void) {
  int i,j; scanf("%d",&n);
  for (i = 0; i < n; ++i) {
    for (j = 0; j < i+1; ++j) {
      scanf("%d", &a[i][j]);
    }
  }
  memset(dp, -1, sizeof(dp));
  for (i = 0; i < n; ++i) dp[n-1][i] = a[n-1][i];
  for (i = n-1; i >= 0; --i)
    for (j = 0; j < i+1; ++j)
      f(i, j);
  printf("%d\n", dp[0][0]);
  return 0;
}

  这就是所谓的记忆化搜索  

comments powered by Disqus