【DP】 HDOJ 5009 Paint Pearls

sign。。。比赛的时候已经确定算法了。。。最后卡在实现上。。。赛后AC的。。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 50005
#define maxm 40005
#define eps 1e-10
#define mod 1000000007
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// head

int v[maxn], vv[maxn];
int pre[maxn], pos[maxn], num[maxn];
int dp[maxn];
int vcnt, n;

int search(int x)
{
	int bot = 1, top = vcnt, mid;
	while(top >= bot) {
		mid = (top + bot) >> 1;
		if(vv[mid] == x) break;
		if(vv[mid] > x) top = mid-1;
		else bot = mid+1;
	}
	return mid;
}
int cmp(int a, int b)
{
	return a < b;
}
void init(void)
{
	memset(dp, 0, sizeof dp);
	memset(pre, -1, sizeof pre);
	memset(pos, -1, sizeof pos);
	memset(num, -1, sizeof num);
}
void read(void)
{
	for(int i = 1; i <= n; i++) scanf("%d", &v[i]), vv[i] = v[i];
	int j = 2;
	sort(vv+1, vv+n+1, cmp);
	for(int i = 2; i <= n; i++)
		if(vv[i] != vv[i-1]) vv[j++] = vv[i];
	vcnt = j - 1;
	for(int i = 1; i <= n; i++) v[i] = search(v[i]);
}
void work(void)
{
	int t = sqrt((double)n);
	t += 2;
	for(int i = 1; i <= n; i++) pre[i] = num[v[i]], num[v[i]] = i;
	for(int i = 1; i <= n; i++) {
		dp[i] = dp[i-1] + 1;
		if(pre[i] == -1) {
			for(int k = t; k >= 2; k--) pos[k] = pos[k-1];
			pos[1] = i;
		}
		else {
			for(int k = t; k >= 2; k--)
				if(pos[k] <= pre[i]) continue;
				else pos[k] = pos[k-1];
			if(v[i] != v[i-1]) pos[1] = i;
		}
		pos[t] = -1;		
		for(int k = 1; k <= t; k++) {
			if(pos[k] == -1) break;
			else dp[i] = min(dp[pos[k]-1] + k * k, dp[i]);
		}
	}
	printf("%d\n", dp[n]);
}
int main(void)
{
	while(scanf("%d", &n)!=EOF) {
		init();
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)