Paint Pearls
problem DescriptionLee has a string of n pearls. In the beginning, all the pearls has 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 would be painted to
their target colors.When he paints a string which have K different target colors, Lee would cost K2 points.
Now, the Lee wants to the cost as few as possible to get the his ideal string. You should tell him the minimal cost.
InputThere is multiple test cases. Please process till EOF.
For each test case, the first line contains an integer n (1≤n≤5x104), indicating the number of pearls. The second line contains A1,A2,..., a (1≤ai≤109) indicating the target color of each pearl.
OutputFor each test case, the output of the minimal cost of a line.
Sample Input31 3 3103 4 2 4 4 2 4 3 2 2
Sample Output27
Test instructions
Give you an array, each value represents a color, each time you choose an interval to apply the color, the price is the square of the number of colors in the interval, paint all the arrays, ask you the minimum cost is how much
Exercises
Set Dp[i] to the minimum cost of the number of previous I,
Then the transfer is dp[i] = min{dp[j]+cal (j+1,i) ^2} Cal calculates the number of colors in the interval
Apparent timeout;
When you traverse from the i-1 to 0 to find the smallest dp[j]+cal (j+1,i) ^2, some TV can jump, that is in the k~i-1 inside, you can skip, this with a doubly linked list implementation
There is also an optimization: when traversing forward, the different number of squares has exceeded the value of the individual coloring namely CAL (J+1,i) ^2>i Jump directly
#include <iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>#include<map>using namespacestd;Const intN = 1e5+Ten, M = 2e2+ One, inf = 2e9, mod = 1e9+7;intDp[n],a[n],pre[n],nex[n],n;map<int,int>MP;intMain () { while(SCANF ("%d", &n)! =EOF) {mp.clear (); Memset (DP,127,sizeof(DP)); for(intI=1; i<=n;i++) scanf ("%d",&A[i]); for(intI=1; i<=n;i++) nex[i]=i+1, pre[i]=i-1; dp[0]=0, pre[0]=-1; for(intI=1; i<=n;i++) { if(!mp[a[i]]) mp[a[i]]=i; Else { intID =Mp[a[i]]; Nex[pre[id]]=Nex[id]; Pre[nex[id]]=Pre[id]; Mp[a[id]]=i; } intnum =0; for(intj=pre[i];j!=-1; j=Pre[j]) {num++; Dp[i]= Min (dp[i],dp[j]+num*num); if(Num*num>i) Break; }} printf ("%d\n", Dp[n]); } return 0;}
HDU 5009 Paint pearls bidirectional linked list optimization DP