首页 > 代码库 > hdu 5009 Paint Pearls (动态规划)
hdu 5009 Paint Pearls (动态规划)
Paint Pearls
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2359 Accepted Submission(s): 761
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.
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.
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
因为颜色范围比较大,可以对颜色进行离散化便于处理。然后暴力,G++可以通过。
#include<stdio.h> #include<string.h> #include<iostream> #include<vector> #include<algorithm> using namespace std; #define ll __int64 #define N 50005 const int inf=0x1f1f1f1f; int dp[N]; struct node { int val,id,col; }a[N]; vector<int>g; int vis[N]; bool cmpval(node a,node b) { return a.val<b.val; } bool cmpid(node a,node b) { return a.id<b.id; } int main() { int i,j,n,cnt; while(scanf("%d",&n)!=-1) { for(i=1;i<=n;i++) { scanf("%d",&a[i].val); } cnt=1; for(i=2;i<=n;i++) //颜色一样的连续石子保留一个 if(a[i].val!=a[i-1].val) a[++cnt]=a[i]; n=cnt; for(i=1;i<=n;i++) //原始顺序 a[i].id=i; sort(a+1,a+n+1,cmpval); a[1].col=0; cnt=0; for(i=2;i<=n;i++) //为石子颜色重新编号 { if(a[i].val!=a[i-1].val) a[i].col=++cnt; else a[i].col=cnt; } sort(a+1,a+n+1,cmpid); for(i=0;i<=n;i++) dp[i]=inf; dp[0]=0; dp[n]=n; for(i=0;i<n;i++) { cnt=0; for(j=i+1;j<=n;j++) { if(!vis[a[j].col]) { cnt++; vis[a[j].col]=1; g.push_back(a[j].col); } if(dp[i]+cnt*cnt>=dp[n]) //优化 break; dp[j]=min(dp[j],dp[i]+cnt*cnt); } for(j=0;j<cnt;j++) //优化 vis[g[j]]=0; g.clear(); } printf("%d\n",dp[n]); } return 0; }
hdu 5009 Paint Pearls (动态规划)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。