poj 1088(DP+递归)

这题状态方程很容易得到:DP[i][j] = max(DP[i-1][j],DP[i+1][j],DP[i][j-1],DP[i][j+1]) + 1

难点在于边界条件和剪枝,因为这方程的条件是点在map里,且只有递增关系才会变化,如果用循环的话要判断递增,所以用递归比较方便

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;

#define mem(a,b) memset(a,b,sizeof(a))
#define pf printf
#define sf scanf
#define debug printf("!
")
#define INF 10000
#define MAX(a,b) a>b?a:b
#define blank pf("
")
#define LL long long

int n,m,V;
int dp[110][110],map[110][110];

int f(int i,int j)
{
          if(dp[i][j]!=0)
                    return dp[i][j];
          int w,s,a,d;
          if(i-1>=1)
          {
                    if(map[i-1][j]<map[i][j]) s=f(i-1,j)+1;
                    else s=1;
          }
          else s=1;
          if(i+1<=n)
          {
                    if(map[i+1][j]<map[i][j]) w=f(i+1,j)+1;
                    else w=1;
          }
          else w=1;
          if(j-1>=1)
          {
                    if(map[i][j-1]<map[i][j]) a=f(i,j-1)+1;
                    else a=1;
          }
          else a=1;
          if(j+1<=m)
          {
                    if(map[i][j+1]<map[i][j]) d=f(i,j+1)+1;
                    else d=1;
          }
          else d=1;

          int max1 = max(w,s);
          int max2 = max(a,d);
          return max(max1,max2);

}

int main()
{
          int i,j,t;
          while(~sf("%d%d",&n,&m))
          {
                    mem(dp,0);
                    dp[1][1] =1;
                    for(i=1;i<=n;i++)
                    {
                              for(j = 1;j<=m;j++)
                                        sf("%d",&map[i][j]);
                    }
                    int max = 0;
                    for(i=1;i<=n;i++)
                    {
                              for(j = 1;j<=m;j++)
                              {
                                        dp[i][j]=f(i,j);
                                        if(max<dp[i][j]) max = dp[i][j];
                              }
                    }
                    pf("%d
",max);

          }
}
原文地址:https://www.cnblogs.com/qlky/p/5155378.html