HDU-2686 Matrix 双线程DP

题目链接

#include <stdio.h>
#include <string.h>
#include <iostream>
#include<functional>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 35;
const int inf = 1<<30;
int n;
int map[maxn][maxn],dp[maxn][maxn][maxn][maxn];
int Max( int a,int b,int c,int d )
{
	if( a < b ) a = b;
	if( a < c ) a = c;
	if( a < d ) a = d;
	return a;
}
int main()
{
    #ifndef ONLINE_JUDGE  
	freopen("data.txt","r",stdin);  
    #endif 	
	while( scanf("%d",&n) != EOF ){
		memset( dp,0,sizeof(dp) );
		for( int i = 1; i <= n; i ++ )
			for( int j = 1; j <= n; j ++ )
				scanf("%d",&map[i][j]);
		for( int i = 1; i <= n; i ++ ){
			for( int j = 1; j <= n; j ++ ){
				for( int x = 1; x < i; x ++ ){
					int y = i + j - x;
					dp[i][j][x][y] =   Max( dp[i-1][j][x-1][y],dp[i-1][j][x][y-1],dp[i][j-1][x-1][y],dp[i][j-1][x][y-1] ) + map[i][j] + map[x][y];
				}
			}
		}
		printf("%d\n",dp[n][n-1][n-1][n] + map[1][1] + map[n][n]);
	}
	return 0;
}



#include <stdio.h>
#include <string.h>
#include <iostream>
#include<functional>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 35;
const int inf = 1<<30;
int n;
int map[maxn][maxn],dp[maxn][maxn][maxn][maxn];
bool vis[maxn][maxn][maxn][maxn];
int Max( int a,int b,int c,int d )
{
	if( a < b ) a = b;
	if( a < c ) a = c;
	if( a < d ) a = d;
	return a;
}
int dfs( int a,int b,int c,int d )
{
	if( a<1 || a>n || b<1 || b>n || c<1 || c>n || d<1 || d>n ) //判断是否越界
	{
		return 0;
	}
	if( vis[a][b][c][d] == 1 )                                
		return dp[a][b][c][d];
	vis[a][b][c][d] = 1; 
	dp[a][b][c][d] = Max( dfs( a-1,b,c-1,d ),dfs( a-1,b,c,d-1 ),dfs( a,b-1,c-1,d ),dfs( a,b-1,c,d-1 ) ) + map[a][b] + map[c][d];
	return dp[a][b][c][d];
}
int main()
{
	#ifndef ONLINE_JUDGE  
	freopen("data.txt","r",stdin);  
	#endif 	
	while( scanf("%d",&n) != EOF )
	{
		memset(dp,0,sizeof(dp));
		memset(vis,0,sizeof(vis));
		for( int i = 1; i <= n; i ++ )                
		{
			for( int j = 1; j <= n; j ++ )
			{
				scanf("%d",&map[i][j]);
				vis[i][j][i][j] = 1;            //把两条路走到相同点的情况标记成1
			}
		}
		printf("%d\n",dfs(n,n-1,n-1,n)+map[1][1]+map[n][n]);  
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值