[CSP-S Simulation Test]: Cake (section DP)

Topic Portal (internal title 34)


Input Format

The first line, a positive integer $ n $.
Second row, $ n $ positive integers $ a_i $, $ a_i $ ensure equal to each other.


Output Format

Line represents a maximum integer size of the sum of the cake Mamiya Takuji obtained.


Sample

Sample input 1:

5
2 8 1 10 9

Sample output 1:

18

Sample input 2:

8
1 10 4 5 6 2 9 3

Sample Output 2:

26


Data range and tips

Sample 1 explanation:

The optimal solution is: Takuji Jun Selection of $ 2 $ blocks; rain Kou sauce selected from the first $ 1 $ block; Takuji Jun Selection of $ 5 $ block; rain Kou sauce selected from the group of $ 4 $ block; Takuji Jun Selection of $ 3 $ block.

data range:

For $ 32 \% $ data, $ 1 \ leqslant n \ leqslant 20 $.
For $ 64 \% $ data, $ 1 \ leqslant n \ leqslant 30 $.
For $ 100 \% $ data, $ 1 \ leqslant n \ leqslant 2,000,1 \ leqslant a_i \ leqslant {10} ^ 9 $, $ equal to each other to ensure that $ a_i.


answer

$ $ Considering the DP, defined $ dp [i] [j] $ interval represents a further get finished $ [i, j] $ on the size of the cake and the maximum length is determined according to the parity who took the can.

Time complexity: $ \ Theta (n ^ 2) $.

Desired points: $ 100 $ points.

The actual sub-: $ 100 $ points.


Code time

#include<bits/stdc++.h>
using namespace std;
int n;
long long a[2010];
long long dp[2010][2010];
long long ans;
int get(int x){if(x>n)x-=n;if(!x)x+=n;return x;}
long long DP(int l,int r,int x)
{
	if(x>=n-1)return 0;
	if(dp[l][r]!=-1)return dp[l][r];
	dp[l][r]=0;
	int ll=l,rr=r;
	int lft=get(l-1),rht=get(r+1);
	if(a[lft]>a[rht])l=lft;
	else r=rht;
	lft=get(l-1);
	rht=get(r+1);
	dp[ll][rr]=max(DP(lft,r,x+2)+a[lft],DP(l,rht,x+2)+a[rht]);
	return dp[ll][rr];
}
int main()
{
	memset(dp,-1,sizeof(dp));
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
	for(int i=1;i<=n;i++)ans=max(ans,a[i]+DP(i,i,1));
	printf("%lld",ans);
	return 0;
}

rp ++

Guess you like

Origin www.cnblogs.com/wzc521/p/11494076.html