Paint Pearls
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2468 Accepted Submission(s): 807
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.
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.
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
题意:给n个无色珠子染色,每次可以选择染任意的区间,每次染色的代价是区间内不同颜色珠子数量的平方,求最小代价。
思路:我是真的没想到n2的dp居然能过!!而且还需要特殊的姿势:dp[i] = max{dp[j] + p * p}( i<j<=m),不知道是不是我写搓了,如果将j的范围换做0<=j<i,就会tle。另外不能用memset,这个我本来没有多想,结果tle好多次,一直以为memset挺快的,后来想想也是个O(n)。。。
AC代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
using namespace std;
bool vis[50010];
int a[50010], b[50010], dp[50010], f[50010], ff = 0;
map<int, int>mp;
main() {
int n;
while(~scanf("%d", &n)) {
memset(dp, 0, sizeof dp);
mp.clear();
int cnt = 0, m = 0;
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
if(mp.find(a[i]) == mp.end()) mp[a[i]] = cnt++;
if(m == 1 || a[i] != a[i - 1]) b[++m] = a[i];
}
int k = sqrt(m) + 1;
for(int i = 1; i <= m; i++) b[i] = mp[b[i]], dp[i] = 1 << 30;
dp[0] = 0, dp[m] = m;
bool flag = false;
for(int i = 0; i < m; i++) {
int p = 0;
for(int j = 0; j < ff; j++) vis[f[j]] = false;
ff = 0;
for(int j = i + 1; j <= m; j++) {
if(!vis[b[j]]) vis[b[j]] = true, p++, f[ff++] = b[j];
if(p >= k || dp[i] +p * p >= dp[m]) break;
dp[j] = min(dp[j], dp[i] + p * p);
}
}
printf("%d\n", dp[m]);
}
}