Paint Pearls
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2089 Accepted Submission(s): 687
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
Source
Recommend
解题思路:
dp[i]表示长度为i的最小花费,那么显然转移方程是dp[i]=min(dp[i],dp[j]+num(i+1,j));
长度为L的串答案最多是L,所以num(i+1,j)>L的话,有单调性后面的dp都不用考虑了。
然后就是STL(list+map)一通乱搞。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <vector>
#include <list>
#define maxn 50010
using namespace std;
int n,c[maxn],dp[maxn];
vector<int> v;
void read(){
for(int i=1;i<=n;i++) scanf("%d",&c[i]);
}
void init(){
v.clear();
v.push_back(0);
v.push_back(c[1]);
int last=c[1];
for(int i=2;i<=n;i++){
if(c[i]!=last){
last=c[i];
v.push_back(c[i]);
}
}
}
void solve(){
init();
int nn=v.size();
for(int i=0;i<nn;i++) dp[i]=i;
list<int> lis;
list<int>::reverse_iterator at;
map<int,pair<list<int>::iterator,int> > q;
map<int,pair<list<int>::iterator,int> >::reverse_iterator it;
int ct=0;
lis.push_back(0);
q[0]=make_pair(--lis.end(),0);
for(int i=1;i<nn;i++){
if(q.find(v[i])!=q.end()){
lis.erase(q[v[i]].first);
q.erase(q.find(v[i]));
}
lis.push_back(i);
q[v[i]]=make_pair(--lis.end(),i);
int k=0;
for(at=lis.rbegin();at!=lis.rend();at++,k++){
int tmp=dp[*at]+k*k;
if(tmp<dp[i]) dp[i]=tmp;
if(k*k>i) break;
}
}
printf("%d\n",dp[nn-1]);
}
int main(){
while(~scanf("%d",&n)){
read();
solve();
}
return 0;
}