Lee has a string of n pearls. In the beginning, all the pearls have no color. He plans to color the pearls to make it more fascinating. He drew his ideal pattern of the string on a paper and asks for your help.
In each operation, he selects some continuous pearls and all these pearls will be painted to their target colors. When he paints a string which has k different target colors, Lee will cost k 2 points.
Now, Lee wants to cost as few as possible to get his ideal string. You should tell him the minimal cost.
Input
There are multiple test cases. Please process till EOF.
For each test case, the first line contains an integer
n(1≤n≤5×104)
n
(
1
≤
n
≤
5
×
10
4
)
, indicating the number of pearls. The second line contains
a1,a2,...,an(1≤ai≤109)
a
1
,
a
2
,
.
.
.
,
a
n
(
1
≤
a
i
≤
10
9
)
indicating the target color of each pearl.
Output
For each test case, output the minimal cost in a line.
Sample Input
3
1 3 3
10
3 4 2 4 4 2 4 3 2 2
Sample Output
2
7
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#define maxx 50005
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
int a[maxx];
int dp[maxx];
int pre[maxx],_next[maxx];
inline int _min(int a,int b)
{
return a>b?b:a;
}
int main()
{
int n;
while(scanf("%d",&n)==1)
{
for(int i=1;i<=n;i++) scanf("%d",a+i);
for(int i=1;i<=n;i++)
{
pre[i]=i-1;
_next[i]=i+1;
}
map<int,int>_map;
dp[0]=0;
pre[0]=-1;
for(int i=1;i<=n;i++)
{
if(!_map[a[i]])
_map[a[i]]=i;
else
{
int ind=_map[a[i]];
_next[pre[ind]]=_next[ind];
pre[_next[ind]]=pre[ind];
_map[a[i]]=i;
}
int _count=0;
dp[i]=i;
for(int j=pre[i];~j;j=pre[j])
{
_count++;
dp[i]=_min(dp[i],dp[j]+_count*_count);
if(_count*_count>i)break;
}
}
cout<<dp[n]<<endl;
}
return 0;
}