poj 3176 (dp 金字塔)
阿新 • • 發佈:2019-02-01
Cow Bowling
Then 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.
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.
The highest score is achievable by traversing the cows as shown above.
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 17271 | Accepted: 11531 |
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:7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
Input
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 rulesSample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
Hint
Explanation of the sample:7 * 3 8 * 8 1 0 * 2 7 4 4 * 4 5 2 6 5
Source
點選開啟題目連結http://poj.org/problem?id=3176
題意:
輸入一個n層的三角形,第i層有i個數,求從第1層到第n層的所有路線中,權值之和最大的路線。
規定:第i層的某個數只能連線走到第i+1層中與它位置相鄰的兩個數中的一個,類似楊輝三角...
分析:資料較小,直接用二維陣列存,簡單的dp;dp[i][j]=maps[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdio.h>
#include<queue>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
#define N 550
int maps[N][N],dp[N][N];
int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF)
{
memset(maps,0,sizeof(maps));
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
scanf("%d",&maps[i][j]);
}
}
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
{
dp[i][j] = maps[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
}
}
printf("%d\n",dp[1][1]);
}
return 0;
}