【DP】 HDOJ 4455 Substrings

DP好题。。。开始的时候以为是线段树。。结果怎么都想不出来。。

#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 1000005
#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 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

LL sum[maxn], dp[maxn];
int pre[maxn], suf[maxn], num[maxn], vis[maxn];
int n, m;
void init(void)
{
	memset(vis, 0, sizeof vis);
	memset(pre, 0, sizeof pre);
	memset(sum, 0, sizeof sum);
}
void read(void)
{
	for(int i = 1; i <= n; i++) scanf(num[i]);
	scanf("%d", &m);
}
void work(void)
{
	int x, mx = 0;
	for(int i = n; i >= 1; i--)
		if(!vis[num[i]]) vis[num[i]] = 1, suf[n-i+1] = suf[n-i] + 1;
		else suf[n-i+1] = suf[n-i];
	for(int i = 1; i <= n; i++) sum[i - pre[num[i]]]++, mx = max(mx, i - pre[num[i]]), pre[num[i]] = i;
	sum[mx + 1] = 0;
	for(int i = mx; i >= 0; i--) sum[i] += sum[i+1];
	for(int i = 1; i <= n; i++) dp[i] = dp[i-1] - suf[i-1] + sum[i];
	while(m--) scanf("%d", &x), printf("%I64d\n", dp[x]);
}
int main(void)
{
	while(scanf("%d", &n), n != 0) {
		init();
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)