Paint Pearls(HDU 5009)

Paint Pearls

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2221    Accepted Submission(s): 719


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 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
 

Source
 

题意:
给你一个数列,每个数代表一种颜色,每次选一个区间覆盖,覆盖的费用是区间内颜色种类数的平方,直到覆盖整个数列,求最小花费。

分析:
利用dp,转移方程:dp[i] = min(dp[i], dp[j]+k*k); dp[i]表示在第i个数这里时的最小费用。由于时间复杂度为O(n*n),故会超时。所以需要各种剪枝。我已TLE n次了==。 这里重点就是如何快速查询 j+1~i 有几种不同元素。正解应该是利用什么链表吧,不过我不会,只好利用各种赖皮技术。我利用两个剪枝:1.当总的颜色种类很少并且n很大时,可直接输出种类的平方。2.因为总的颜色种类最多n,故最小花费最多也是50000。所以当计算到比k*k>n时就不用继续算了,直接就是n。

不想说那么多了,其实我只是想练一下 dp 的,谁知道有这么多麻烦,其实这题最后是各种乱搞过的。
非正解(乱搞)代码:
#include<stdio.h>
#include<set>
#include<algorithm>
using namespace std;
#define INF 1<<30
const int N = 50010;

int main()
{
    int n, i, j, a[N], k[N], dp[N];

    while(~scanf("%d", &n))
    {
        set<int> m;
        for(i=1; i<=n; i++)
        {
            scanf("%d", a+i);
            m.insert(a[i]);
        }
        int x = m.size();
        if(n > 25 && x < 5) //快速算出类似1 2 1 2 1 2..的这种
        {
            printf("%d\n", x*x);
            continue;
        }
        for(i=1; i<=n; i++)
        {
            dp[i] = (i==1 ? 1 : INF);
            m.clear();
            m.insert(a[i]);
            k[i] = m.size();
            for(j=i-1; j>=0; j--)
            {
                m.insert(a[j]);
                k[j] = m.size();
                if(k[j+1] > 5) break; //原谅我这里耍赖皮==
                dp[i] = min(dp[i], dp[j]+k[j+1]*k[j+1]);
            }
        }
        printf("%d\n", dp[n]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值