①递归计算:
int solve(int i, int j) {
return a[i][j] + (i == n ? 0 : max(solve(i + 1, j), solve(i + 1, j + 1)));
}
②:递推计算:
int solve(int n) {
int i, j;
for (j = 1; j <= n; j++)
d[n][j] = a[n][j];
for (i = n - 1; i >= 1; i--)
for (j = 1; j <= i; j++)
d[i][j] = a[i][j] + max(d[i + 1][j], d[i + 1][j + 1]);
}
③记忆化搜索:
int solve(int i, int j) {
if (d[i][j] >= 0)
return d[i][j];
d[i][j] = a[i][j] + (i == n ? 0 : max(solve(i + 1, j), solve(i + 1, j + 1)));
}
bjfu 1096 拾宝(类似于数字三角形)
题目链接:http://acm.bjfu.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1096
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 100
int a[N][N],d[N][N];
int n;
int solve(int i,int j)
{
if(d[i][j]>=0)
return d[i][j];
return d[i][j]=a[i][j]+(i==n?0:max(solve(i+1,j),solve(i+1,j+1)));
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(d,-1,sizeof(d));
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
scanf("%d",&a[i][j]);
printf("%d\n",solve(1,1));
}
return 0;
}
hdu 1176 免费馅饼(增强版数字三角形)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1176
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 100001
int d[N][11];
int solve(int end)
{
int i,j;
for(i=end-1;i>=0;i--)
for(j=0;j<=10;j++)
{
int max=d[i+1][j];
if(j!=0&&max<d[i+1][j-1])
max=d[i+1][j-1];
if(j!=10&&max<d[i+1][j+1])
max=d[i+1][j+1];
d[i][j]+=max;
}
return d[0][5];
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
memset(d,0,sizeof(d));
int x,T;
int end=-1;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&T);
d[T][x]++;
if(end<T)
end=T;
}
printf("%d\n",solve(end));
}
return 0;
}