递推DP POJ 1163 The Triangle

题目传送门

题意:找一条从顶部到底部的一条路径,往左下或右下走,使得经过的数字和最大。

分析:递推的经典题目,自底向上递推。当状态保存在a[n][j]时可省去dp数组,空间可优化。

代码1:

/************************************************
* Author :Running_Time
* Created Time :2015-9-1 11:17:04
* File Name :POJ_1163.cpp
************************************************/ #include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std; #define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int N = 1e2 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int a[N][N];
int dp[N][N]; int main(void) {
int n;
while (scanf ("%d", &n) == 1) {
for (int i=1; i<=n; ++i) {
for (int j=1; j<=i; ++j) {
scanf ("%d", &a[i][j]);
if (i == n) dp[i][j] = a[i][j];
}
}
for (int i=n-1; i>=1; --i) {
for (int j=1; j<=i; ++j) {
dp[i][j] = max (dp[i+1][j], dp[i+1][j+1]) + a[i][j];
}
}
printf ("%d\n", dp[1][1]);
} return 0;
}

代码2(空间优化):

/************************************************
* Author :Running_Time
* Created Time :2015-9-1 11:18:25
* File Name :POJ_1163_2.cpp
************************************************/ #include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std; #define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int N = 1e2 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int a[N][N]; int main(void) {
int n;
while (scanf ("%d", &n) == 1) {
for (int i=1; i<=n; ++i) {
for (int j=1; j<=i; ++j) {
scanf ("%d", &a[i][j]);
}
}
for (int i=n-1; i>=1; --i) {
for (int j=1; j<=i; ++j) {
a[n][j] = max (a[n][j], a[n][j+1]) + a[i][j];
}
}
printf ("%d\n", a[n][1]);
} return 0;
}

  

上一篇:2016年最佳Linux发行版排行榜


下一篇:BZOJ 3944: Sum [杜教筛]