HDU 5009-Paint Pearls-dp+双向链表

Description

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 k2 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), indicating the number of pearls. The second line contains a1,a2,…,an (1 ≤ ai ≤ 109) 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

题目大意:

一排n个珠子需要被染上特定的颜色。每次操作可以选择连续的若干个(子串)染上其特定的颜色,花费是这个子串不同的颜色数的平方。由于是直接染成特定的颜色,一个珠子只需要被染一次。问n个珠子全被染成特定颜色所需要的最小花费。

核心思想:

dp+双向链表
dp[i]表示染前i个珠子所需要的最小花费。
状态转移方程:
dp[i]=min(dp[i],dp[j]+cnt*cnt),0<=j<i,cnt为[j+1,i]内不同的颜色数
如果j从0遍历至i-1,时间复杂度是n2,会超时。
1、由于重复出现的颜色我们只需要计算一次,可以用双向链表维护当前各个颜色最近一次出现的位置即可(旧位置从链表中移除)。
2、若每个珠子逐个染色,花费为n,当 cnt>= sqrt (n) 时,解不可能优于n,break。
时间复杂度n1.5

代码如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=5e4+20;
//pre存前驱,ne存后继,vis存最新位置,b离散化,a存目标颜色 
int pre[N],ne[N],vis[N],b[N],a[N],dp[N];
int getid(int x,int en)
{
	return lower_bound(b+1,b+en,x)-b;
}
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		//输入及初始化
		dp[0]=0,dp[n]=n; 
		pre[0]=-1;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			//连通必绑定 
			if(a[i]==a[i-1])
			{
				i--;
				n--;
				continue;
			}
			b[i]=a[i];
			pre[i]=i-1;
			ne[i]=i+1;
			vis[i]=0;
			dp[i]=inf;
		}
		//离散化,方便vis 
		sort(b+1,b+n+1);
		int en=unique(b+1,b+n+1)-b;
		//dp
		for(int i=1;i<=n;i++)
		{
			int id=getid(a[i],en);
			//存在旧位置,将旧位置从双向链表中移除 
			if(vis[id])
			{
				int p=vis[id];
				pre[ne[p]]=pre[p];
				ne[pre[p]]=ne[p];
			}
			//最新位置出现 
			vis[id]=i;
			//状态转移 
			int cnt=0;
			for(int j=pre[i];j>-1;j=pre[j])
			{
				cnt++;
				dp[i]=min(dp[i],dp[j]+cnt*cnt);
				//及时break 
				if(cnt*cnt>i)
					break;
			}
		}
		//输出 
		printf("%d\n",dp[n]);
	}	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值