原题链接


D. Maximum path



time limit per test



memory limit per test



input



output


3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.

Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.


Input



n (1 ≤ n ≤ 105)  — the number of columns in the table.

n integers each  — the description of the table. The j-th number in the i-th line corresponds to the cell aij(9 ≤ aij ≤ 109) of the table.


Output



Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.


Examples



input



3 1 1 1 1 -1 1 1 1 1



output



7



input



5 10 10 10 -1 -1 -1 10 10 10 10 -1 10 10 10 10



output



110


向回走两格以上的路径可以转化为不向回走的路径,所以只需要考虑向回走一格的路径即可


#include <iostream>
#include <cstdio> 
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cmath>
#define maxn 100005
#define INF 1e18
#define MOD 1000000007
typedef long long ll;
using namespace std;

ll dp[3][maxn], num[3][maxn];
ll sum(int i, int j, int k){
	if(j > k)
	 swap(j, k);
	ll p = 0;
	for(int h = j; h <= k; h++)
	 p += num[h][i];
	return p;
}
int main(){
//	freopen("in.txt", "r", stdin);
	int n;
	scanf("%d", &n);
	for(int i = 0; i < 3; i++)
	 for(int j = 1; j <= n; j++){
	  scanf("%I64d", &num[i][j]);
	  dp[i][j] = -INF;
    }
    dp[0][0] = 0;
    dp[0][1] = num[0][1];
    dp[1][1] = (ll)num[0][1] + num[1][1];
    dp[2][1] = (ll)num[0][1] + num[1][1] + num[2][1];
    for(int i = 2; i <= n; i++){
     for(int j = 0; j < 3; j++)
     	for(int k = 0; k < 3; k++){
     	    dp[j][i] = max(dp[j][i], dp[k][i-1] + sum(i, j, k));
     	}
     	ll p = sum(i-1, 0, 2) + sum(i, 0, 2);
     	dp[0][i] = max(dp[0][i], dp[2][i-2] + p);
     	dp[2][i] = max(dp[2][i], dp[0][i-2] + p);
   }
   printf("%I64d\n", dp[2][n]);
   return 0;
}