Educational Codeforces Round 17-D. Maximum path

原題鏈接

D. Maximum path
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a rectangular table 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

The first line contains an integer n (1 ≤ n ≤ 105)  — the number of columns in the table.

Next three lines contain n integers each  — the description of the table. The j-th number in the i-th line corresponds to the cell aij( - 109 ≤ 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章