HDOJ 5009 Paint Pearls,hdoj5009

來源:互聯網
上載者:User

HDOJ 5009 Paint Pearls,hdoj5009


DP + 最佳化 ,因為花費是n^2的,所以num×num 大於 DP【i】的時候就可以跳出了。。。。

Paint Pearls Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1245    Accepted Submission(s): 395


Problem DescriptionLee 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. 
InputThere 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. 
OutputFor 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
 
Source2014 ACM/ICPC Asia Regional Xi'an Online 
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <map>using namespace std;int n,a[50050],b[50050],last[50050];int dp[50050];map<int,int> mp;int fa[50050];int find(int x){if(x==fa[x]) return x;return fa[x]=find(fa[x]);}void bing(int x,int y){int X=find(x),Y=find(y);if(X==Y) return ;fa[Y]=X;}int main(){while(scanf("%d",&n)!=EOF){for(int i=1;i<=n;i++){scanf("%d",a+i);b[i]=a[i];}sort(b+1,b+n+1);int cnt=unique(b,b+n+1)-b;for(int i=1;i<cnt;i++){mp[b[i]]=i;}for(int i=0;i<=n;i++){a[i]=mp[a[i]];fa[i]=i;last[i]=-1;}for(int i=1;i<=n;i++){if(last[a[i]]!=-1){bing(last[a[i]]-1,last[a[i]]);}last[a[i]]=i;dp[i]=i;int num=0;for(int j=i;j>0;j=find(j-1)){num++;if(num*num>dp[i]) break;int next=find(j-1);dp[i]=min(dp[i],dp[next]+num*num);}}printf("%d\n",dp[n]);}return 0;}







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.