题目描述
设有 N×N 的方格图,我们在其中的某些方格中填入正整数,而其它的方格中则放入数字 0 ,如下图所示:
某人从图中的左上角 A 出发,可以向下行走,也可以向右行走,直到到达右下角的 B 点
在走过的路上,他可以取走方格中的数(取走后的方格中将变为数字 0 )
此人从 A 点到 B 点共走了两次,试找出两条这样的路径,使得取得的数字和为最大
输入格式
第一行为一个整数 N ,表示 N×N 的方格图
接下来的每行有三个整数,第一个为行号数,第二个为列号数,第三个为在该行、该列上所放的数
行和列编号从 1 开始
一行“ 0 0 0 ”表示结束
输出格式
输出一个整数,表示两条路径上取得的最大的和
数据范围
N≤10
输入样例:
8
2 3 13
2 6 6
3 5 7
4 4 14
5 2 21
5 6 4
6 3 15
7 2 14
0 0 0
输出样例:
67
代码
#include<bits/stdc++.h>
using namespace std;
#define ioio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n";
#define debug(x) cout<<#x<<":"<<x<<endl;
#define L(k) k<<1
#define R(k) k<<1|1
#define P pair
#define P1 first
#define P2 second
#define u_map unordered_map
#define p_queue priority_queue
typedef long ll;
const double eps = 1e-6;
const double E = 2.718;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int INF2 = (1 << 31);
const int N = 15 + 7;
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
/*-----------------------------------*/
int n;
int ma[N][N];
int dp[N][N][N];
int main() {
ioio
cin >> n;
int u, v, w;
while (cin >> u >> v >> w, u && v && w)
ma[u][v] = w;
for (int k = 2; k <= n * 2; k++)
for (int i1 = 1; i1 <= n; i1++)
for (int i2 = 1; i2 <= n; i2++) {
int j1=k-i1,j2=k-i2;
if(j1>=1&&j1<=n&&j2>=1&&j2<=n){
int t=ma[i1][j1];
if(i1!=i2)t+=ma[i2][j2];
int &x=dp[k][i1][i2];
x=max(x,dp[k-1][i1-1][i2-1]+t);
x=max(x,dp[k-1][i1-1][i2]+t);
x=max(x,dp[k-1][i1][i2-1]+t);
x=max(x,dp[k-1][i1][i2]+t);
}
}
cout<<dp[2*n][n][n]<<endl;
return 0;
}