poj3176(Cow Bowling)
Description
The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Output
Line 1: The largest sum achievable using the traversal rules
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
最基础的数塔dp了,维数可以降到一维来优化空间,不过这样要注意循环顺序,以免覆盖之前结果
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <limits>
#include <new>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double EPS = 1e-8;
const int MAXN = 360;
int dx[] = {0, 1, 0, -1}, dy[] = {-1, 0, 1, 0};
int main()
{
int n;
int s[MAXN][MAXN], dp[MAXN];
cin >> n;
for (int i = 0; i < n; ++i)
for (int j = 0; j <= i; ++j)
scanf("%d", &s[i][j]);
for (int i = 0; i < n; ++i)
dp[i] = s[n-1][i];
for (int i = n-2; i >= 0; --i)
for (int j = 0; j <= i; ++j)
dp[j] = max(dp[j], dp[j+1]) + s[i][j];
cout << dp[0] << endl;
return 0;
}
算法码上来 文章被收录于专栏
公众号「算法码上来」。godweiyang带你学习算法,不管是编程算法,还是深度学习、自然语言处理算法都一网打尽,更有各种计算机新鲜知识和你分享。别急,算法码上来。