标签:text namespace 思路 follow span hdu mission target new
http://acm.hdu.edu.cn/showproblem.php?pid=4455
7 1 1 2 3 4 4 5 3 1 2 3 0
7 10 12
/**
hdu4455 dp
题目大意:给定一个序列,求其全部长度为w的子区间中不同元素的个数之和
解题思路:这个题与其说是dp还不如说是递推好一些。首先定义c[i]表示前面近期的与其同样的数的距离是i的数的个数,sum[i]表示前面近期的与其同样的数
的距离大于等于i的数的个数。num[i]表示最后一个长度为i的区间含有的不同数的个数。dp[1]=n,dp[i]=dp[i-1]-num[i]+sum[i];
*/
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
using namespace std;
const int maxn=1000050;
typedef long long LL;
int c[maxn],sum[maxn],num[maxn],pre[maxn];
LL dp[maxn];
int n,m,a[maxn];
int main()
{
while(~scanf("%d",&n))
{
if(n==0)break;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
memset(pre,0,sizeof(pre));
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
c[i-pre[a[i]]]++;
pre[a[i]]=i;
}
sum[n]=c[n];
for(int i=n-1;i>0;i--)
{
sum[i]=sum[i+1]+c[i];
}
memset(c,0,sizeof(c));///数组重用
c[a[n]]=1;
num[1]=1;
for(int i=2;i<=n;i++)
{
if(c[a[n-i+1]]==0)
{
num[i]=num[i-1]+1;
c[a[n-i+1]]=1;
}
else
{
num[i]=num[i-1];
}
}
dp[1]=n;
for(int i=2;i<=n;i++)
{
dp[i]=dp[i-1]-num[i-1]+sum[i];
}
scanf("%d",&m);
for(int i=0;i<m;i++)
{
int x;
scanf("%d",&x);
printf("%I64d\n",dp[x]);
}
}
return 0;
}
标签:text namespace 思路 follow span hdu mission target new
原文地址:http://www.cnblogs.com/yangykaifa/p/7221309.html