要走兩次因此,考慮一個四維的陣列來實現,然後如果i=k&&j==l的話記得減一次即得到答案。
點選檢視程式碼
#include <iostream>
#include <stack>
#include <cmath>
#include <algorithm>
#include <set>
#include <vector>
#include <climits>
#include <string.h>
#include <map>
#include <queue>
#include <list>
#include <cmath>
#include <iomanip>
#define int long long
#define ios ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define lc u<<1
#define rc u<<1|1
#define gcd __gcd
#define double long double
#define endl "\n"
#define INF LLONG_MAX
#define mod 1000000007
#define N 15
const double PI = 3.14159265358979323846;
using namespace std;
int dp[N][N][N][N], a[N][N],n;//dp[1][j][k][l]表示第一次和第二次的最優解
signed main()
{
ios;
cin >> n;
while (1)
{
int x, y,z; cin >> x >> y>>z;
if (x == 0 && y == 0&&z==0)break;
a[x][y] = z;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
for (int k = 1; k <= n; k++)
{
for (int l = 1; l <= n; l++)
{
dp[i][j][k][l] = max({ dp[i - 1][j][k - 1][l],dp[i][j - 1][k][l - 1],dp[i][j - 1][k - 1][l],dp[i - 1][j][k][l - 1] }) + a[i][j] + a[k][l];
if (i == k && j == l)dp[i][j][k][l] -= a[i][j];
}
}
}
}
cout << dp[n][n][n][n] << endl;
return 0;
}