Paint Pearls HDU - 5009 (dp+链表优化)

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×10 4), indicating the number of pearls. The second line contains 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<bits/stdc++.h>
#include <tr1/unordered_map>
using namespace std;
typedef long long LL;
#define rep(i,a,b) for(int i=a;i<b;++i)
#define per(i,a,b) for(int i=b-1;i>=a;--i)
#define PB push_back
#define IS insert

unordered_map<int,int>pos;

const int N=5e4+10;

int val[N];
int pre[N],nxt[N];
int dp[N];

int main(){
	int n;
	while(scanf("%d",&n)==1){
		pos.clear();
		rep(i,1,n+1)scanf("%d",&val[i]);
		//??
		pre[0]=0,pre[n+1]=n;
		nxt[0]=1;nxt[n+1]=n+1;
		rep(i,1,n+1){
			pre[i]=i-1;
			nxt[i]=i+1;
		}
		dp[0]=0;
		int limit=sqrt(n+0.5);
		for(int i=1;i<=n;i++){
			int x=val[i];

			dp[i]=dp[i-1]+(val[i]!=val[i-1]);
			if(pos[x]){
				int P=pos[x];
				nxt[pre[P]]=nxt[P];
				pre[nxt[P]]=pre[P];
			}
			pos[x]=i;
			int cnt=0;x=i;

			while(cnt<=limit&&x!=-1){
				dp[i]=min(dp[i],dp[x]+cnt*cnt);
				//printf("i:%d x:%d %d\n",i,x,dp[i]);
				x=pre[x];
				cnt++;
			}
			//printf("i:%d %d\n",i,dp[i]);
		}
		//rep(i,1,n+1)printf("i:%d %d\n",i,dp[i]);
		//rep(i,1,n+1)printf("i:%d pre:%d nxt:%d\n",i,pre[i],nxt[i]);
		printf("%d\n",dp[n]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值