2 3 4 1 -1 1 0 2 -2 4 2 3 5 1 -90 2 2 1 1 1 1
Case #1: 18 Case #2: 4
dp[i][j]=max(dp[i-1][j],dp[i][j-1],dp[i][j+1])
但是这样问题就来了,会出现上下来回走的问题,为避免这样的情况发生,我们把向上走和向下走分开算,把从上到下得到的状态放到一个滚动数组里,然后再算从下到上的,那么我们只要取大的那个就可以了。
AC代码:
//************************************************************************// //*Author : Handsome How *// //************************************************************************// //#pragma comment(linker, "/STA CK:1024000000,1024000000") #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #if defined(_MSC_VER) || __cplusplus > 199711L #define aut(r,v) auto r = (v) #else #define aut(r,v) __typeof(v) r = (v) #endif #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define fur(i,a,b) for(int i=(a);i<=(b);i++) #define furr(i,a,b) for(int i=(a);i>=(b);i--) #define cl(a) memset((a),0,sizeof(a)) #define mp make_pair #define pb push_back #define fi first #define se second #define sc(x) scanf("%d",&x) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair <int, int> pii; const int inf=0x3f3f3f3f; const int inff=-inf; const int mod=1000000007; const double eps=1e-8; const double pi=acos(-1); inline void gn(long long&x){ int sg=1;char c;while(((c=getchar())<'0'||c>'9')&&c!='-');c=='-'?(sg=-1,x=0):(x=c-'0'); while((c=getchar())>='0'&&c<='9')x=x*10+c-'0';x*=sg; } inline void gn(int&x){long long t;gn(t);x=t;} inline void gn(unsigned long long&x){long long t;gn(t);x=t;} inline void gn(double&x){double t;scanf("%lf",&t);x=t;} inline void gn(long double&x){double t;scanf("%lf",&t);x=t;} //---------------------------------------------------------- int dp[111][111]; int fig[111][111]; int tmp[111]; int main() { int T; gn(T); fur(kase,1,T){ int r,c; gn(r);gn(c); fur(i,1,r)fur(j,1,c)gn(fig[i][j]); dp[1][1]=fig[1][1]; fur(i,2,r)dp[i][1]=fig[i][1]+dp[i-1][1]; fur(j,2,c){ tmp[1]=dp[1][j-1]+fig[1][j]; fur(i,2,r)tmp[i]=max(tmp[i-1],dp[i][j-1])+fig[i][j]; //from up to down dp[r][j]=dp[r][j-1]+fig[r][j]; furr(i,r-1,1)dp[i][j]=max(dp[i+1][j],dp[i][j-1])+fig[i][j]; //from down to up fur(i,1,r) if(tmp[i]>dp[i][j])dp[i][j]=tmp[i]; } printf("Case #%d:\n",kase); printf("%d\n",dp[1][c]); } return 0; }