描述
http://poj.org/problem?id=3176
给出一个三角形,每个点可以走到它下面两个点,将所有经过的点的值加起来,问最大的和是多少.
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16826 | Accepted: 11220 |
Description
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
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.
Input
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Output
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
Hint
7
*
3 8
*
8 1 0
*
2 7 4 4
*
4 5 2 6 5
The highest score is achievable by traversing the cows as shown above.
Source
分析
记忆化搜索:
#include<cstdio>
#include<cstring>
#include<algorithm>
using std :: max; const int maxn=;
int a[maxn][maxn],f[maxn][maxn];
int n; int dfs(int i,int j)
{
if(f[i][j]!=-) return f[i][j];
if(i==n) return f[i][j]=a[i][j];
return f[i][j]=a[i][j]+max(dfs(i+,j),dfs(i+,j+));
} void init()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
for(int j=;j<=i;j++)
{
scanf("%d",&a[i][j]);
}
}
memset(f,-,sizeof(f));
} int main()
{
#ifndef ONLINE_JUDGE
freopen("cow.in","r",stdin);
freopen("cow.out","w",stdout);
#endif
init();
printf("%d\n",dfs(,));
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return ;
}
动态规划:
#include<cstdio>
#include<algorithm>
using std :: max; const int maxn=;
int n;
int a[maxn][maxn],f[maxn][maxn]; void solve()
{
for(int i=n-;i>=;i--)
{
for(int j=;j<=i;j++)
{
f[i][j]=max(f[i+][j],f[i+][j+])+a[i][j];
}
}
printf("%d\n",f[][]);
} void init()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
for(int j=;j<=i;j++)
{
scanf("%d",&a[i][j]);
}
}
for(int j=;j<=n;j++) f[n][j]=a[n][j];
} int main()
{
#ifndef ONLINE_JUDGE
freopen("cow.in","r",stdin);
freopen("cow.out","w",stdout);
#endif
init();
solve();
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return ;
}