hdu5009Paint Pearls dp

#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<algorithm>
using namespace std ;
const int maxn = 5e4+10 ;
const int inf = 1e9 ;
int dp[maxn] ;
int a[maxn] ;
map<int,int> ma;
int pre[maxn] ;
int last[maxn] ;
int main()
{
    int n ;
    while(~scanf("%d" , &n))
    {
        int len = 0 ;
        ma.clear() ;
        for(int i = 1;i <= n;i++){
           scanf("%d" , &a[i]) ;
           if(ma[a[i]] == 0){
              ma[a[i]] = ++len ;
           }
        }
        for(int i = 1;i <= n;i++){
            a[i] = ma[a[i]]  ;
            dp[i] = inf ;
        }
        dp[0] = 0 ;
        memset(pre , -1 , sizeof(pre)) ;
        memset(last , 0 , sizeof(last)) ;
        for(int i = n;i > 0;i--){
            if(last[a[i]])
               pre[last[a[i]]] = i ;
            last[a[i]] = i ;
        }
        dp[n] = n ;dp[0] = 0 ;
        for(int i = 0;i <= n;i++){
            int cnt = 0 ;
            for(int j = i+1;j <= n;j++){
                if(pre[j] <= i){
                   cnt++ ;
                }
                int tmp = cnt*cnt ;
                if(tmp + dp[i] > dp[n])
                break ;
                dp[j] = min(dp[j] , dp[i]+tmp) ;
            }
        }
        printf("%d\n" , dp[n]) ;
    }
    return  0 ;
}

你可能感兴趣的:(hdu5009Paint Pearls dp)