您的位置:首页 > 其它

HDU 5009 DP+双端链表

2015-08-30 12:47 375 查看
Paint Pearls

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 2655 Accepted Submission(s): 863

Problem 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

西汉网络赛的题,dp思路好想,主要是对dp的优化上,这里用了一个双端链表,再求dp[i]时,链表里只会存不同的元素,相同的元素会被删除。然后只需沿着链表走就能知道前j个的最优解。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
#include <cmath>

using namespace std;

int a[50010];
int pre[50010];
int nxt[50010];
int dp[50010];

int main()
{
//    freopen("data.in","r",stdin);
int n;
while(scanf("%d",&n)!=EOF){
int i,j,k = 2;
int N = n;
scanf("%d",&a[1]);
pre[0] = -1;
pre[1] = 0;
nxt[1] = 2;
for(i = 2;i<=n;i++){
int tem;
scanf("%d",&tem);
if(tem != a[k-1]){
a[k] = tem;
pre[k] = k-1;
nxt[k] = k+1;
k++;
}
else
N--;
}

memset(dp,0x3f,sizeof(dp));
dp[0] = 0;
map<int ,int >G;
for(i = 1;i<=N;i++){
if(!G.count(a[i]))
G[a[i]] = i;
else{
int id = G[a[i]];
nxt[pre[id]] = nxt[id];
pre[nxt[id]] = pre[id];
G[a[i]] = i;
}

int cnt = 0;
for(j = pre[i];j!=-1;j = pre[j]){
cnt++;
dp[i] = min(dp[i],dp[j]+cnt*cnt);
if(cnt*cnt>i)
break;
}
}
printf("%d\n",dp
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp