HDU 5009 Paint Pearls

来源:互联网 发布:java棕色rgb 编辑:程序博客网 时间:2024/06/06 01:31

Paint Pearls

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


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
31 3 3103 4 2 4 4 2 4 3 2 2
 

Sample Output
27
 

Source
2014 ACM/ICPC Asia Regional Xi'an Online

解题思路:
用f[i][j] 表示 在第i个位置,往前涂j+1种颜色,涂到哪个位置。
dp[i]表示涂到第i个位置,之前的花费最少为多少。
此题的关键是想到,每个长度为i的区间涂的颜色最多为sqrt(i)种,这样f[i][j]数组只需要n*sqrt(n)的复杂度即可求出。
转移方程:
dp[i] = min(dp[i], dp[f[i][j]] + (j + 1) * (j + 1));
#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>#include <vector>#include <queue>#include <stack>#include <set>#include <map>#include <algorithm>#define LL long long #define FOR(i, x, y) for(int i=x;i<=y;i++)using namespace std;const int MAXN = 50000 + 10;const int INF = 0x3f3f3f3f;struct Node{int id, x;bool operator < (const Node& rhs) const{return x < rhs.x;}}node[MAXN];int a[MAXN], vis[MAXN], f[MAXN][250], dp[MAXN];int n;int read(){int res = 0, f = 1; char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-') f *= -1; ch = getchar();}while(ch >= '0' && ch <= '9') {res = res * 10 + ch - '0'; ch = getchar();}return res;}int main(){while(scanf("%d", &n)!=EOF){FOR(i, 1, n){node[i].x = read();node[i].id = i;}sort(node + 1 , node + 1 + n);FOR(i, 1, n){if(node[i].x == node[i-1].x)a[node[i].id] = a[node[i-1].id];elsea[node[i].id] = a[node[i-1].id] + 1;}/*for(int i=1;i<=n;i++)cout << a[i] << ' ';cout << endl;*/FOR(i, 0, n) vis[i] = -1;int nn = (int)(sqrt(n + 0.5));for(int i=1;i<=n;i++){for(int j=1;j<=nn;j++)f[i][j] = -1;}for(int i=1;i<=n;i++){int m = (int)(sqrt(i + 0.5));if(a[i] != a[i-1]) f[i][0] = i - 1;else f[i][0] = f[i-1][0];dp[i] = dp[f[i][0]] + 1;for(int j=1;j<=m;j++) {int x = a[i];if(vis[x] == -1)f[i][j] = f[i-1][j-1];else{int y = vis[x];if(y < f[i-1][j-1])f[i][j] = f[i-1][j-1];else if(y >= f[i-1][j])f[i][j] = f[i-1][j];}dp[i] = min(dp[i], dp[f[i][j]] + (j + 1) * (j + 1));//cout << f[i][j] << ' ';}vis[a[i]] = i;//cout << endl;}printf("%d\n", dp[n]);}return 0;}


0 0
原创粉丝点击