Necklace
frog has nn gems arranged in a cycle, whose beautifulness are a1,a2,…,ana1,a2,…,an. She would like to remove some gems to make them into a beautiful necklacewithout changing their relative order.
Note that a beautiful necklace can be divided into 33 consecutive parts X,y,ZX,y,Z, where
- XX consists of gems with non-decreasing beautifulness,
- yy is the only perfect gem. (A perfect gem is a gem whose beautifulness equals to 1000010000)
- ZZ consists of gems with non-increasing beautifulness.
Find out the maximum total beautifulness of the remaining gems.
Input
The input consists of multiple tests. For each test:
The first line contains 11 integer nn (1≤n≤1051≤n≤105). The second line contains nn integers a1,a2,…,ana1,a2,…,an. (0≤ai≤1040≤ai≤104, 1≤number of perfect gems≤101≤number of perfect gems≤10).
Output
For each test, write 11 integer which denotes the maximum total remaining beautifulness.
Sample Input
6
10000 3 2 4 2 3
2
10000 10000
Sample Output
10010
10000
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+7;
int a[3*maxn],n,ma,bit[10002],dp[maxn*3];
int query(int i)
{
int s=0;
while(i>0)
{
s=max(s,bit[i]);
i-=i&-i;
}
return s;
}
void add(int i,int x)
{
while(i<=10000)
{
bit[i]=max(bit[i],x);
i+=i&-i;
}
}
void slove(int x)
{
memset(dp,0,sizeof(dp));
memset(bit,0,sizeof(bit));
for(int i=x+1,j=1;j<n;j++,i++)
{
if(a[i]==10000)continue;
int tmp=query(10000-a[i])+a[i];
add(10000-a[i],tmp);
dp[i]=max(tmp,dp[i-1]);
}
memset(bit,0,sizeof(bit));
for(int i=x-1,j=1;j<n;j++,i--)
{
if(a[i]==10000)continue;
int tmp=query(10000-a[i])+a[i];
add(10000-a[i],tmp);
dp[i]=max(tmp,dp[i+1]);
}
for(int i=1;i<n;i++)
ma=max(ma,dp[x-i]+dp[x+n-i-1]);
}
int main()
{
while(~scanf("%d",&n))
{
ma=0;
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<=n;i++)a[i+n]=a[i+2*n]=a[i];
for(int i=n+1;i<=2*n;i++)
{
if(a[i]==10000)
{
slove(i);
}
}
printf("%d\n",ma+10000);
}
return 0;
}