HDU 4455 Substrings(dp)

本文介绍了一种高效计算给定长度子串中不同元素总数的方法,并提供了完整的C++实现代码。通过动态规划技巧,算法能在O(n)时间内解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
参考别人的博客:dp[i]=dp[i-1]-A+B;
                           减的A是最后一个长度为i-1的区间的不同数的个数,这个很容易预处理得出来。
                           加的B是第t个数到它上一个数的距离大于i-1的个数.
                           这个B值也容易得出。
                           用s[i]表示离上一个数的距离为i的个数,不断减掉就得到B了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+7;
#define LL long long
int a[maxn];
int fir[maxn],s[maxn],ss[maxn];
LL dp[maxn];
int main()
{
    int n;
	while(scanf("%d",&n)!=EOF && n)
	{
		memset(fir,0,sizeof(fir));
		memset(s,0,sizeof(s));
		for(int i =1;i<=n;i++)
			scanf("%d",&a[i]);
		for(int i = 1;i<=n;i++)
		{
            s[i-fir[a[i]]]++;
			fir[a[i]]=i;
		}
        memset(fir,0,sizeof(fir));
		fir[a[n]]=1;
        ss[1]=1;
		for(int i = 2;i<=n;i++)
		{
            if(fir[a[n-i+1]]==0)
			{
				fir[a[n-i+1]]=1;
				ss[i]=ss[i-1]+1;
			}
			else
				ss[i]=ss[i-1];
		}
		dp[1]=n;
		int sum = n;
		for(int i = 2;i<=n;i++)
		{
			dp[i]=dp[i-1]-ss[i-1];
			sum-=s[i-1];
			dp[i]+=sum;
		}
		int m;
		scanf("%d",&m);
		while(m--)
		{
			int q;
			scanf("%d",&q);
			printf("%lld\n",dp[q]);
		}
	}
}

Description

XXX has an array of length n. XXX wants to know that, for a given w, what is the sum of the distinct elements’ number in all substrings of length w. For example, the array is { 1 1 2 3 4 4 5 } When w = 3, there are five substrings of length 3. They are (1,1,2),(1,2,3),(2,3,4),(3,4,4),(4,4,5) 
The distinct elements’ number of those five substrings are 2,3,3,2,2. 
So the sum of the distinct elements’ number should be 2+3+3+2+2 = 12
 

Input

There are several test cases. 
Each test case starts with a positive integer n, the array length. The next line consists of n integers a 1,a 2…a n, representing the elements of the array. 
Then there is a line with an integer Q, the number of queries. At last Q lines follow, each contains one integer w, the substring length of query. The input data ends with n = 0 For all cases, 0<w<=n<=10 6, 0<=Q<=10 4, 0<= a 1,a 2…a n <=10 6
 

Output

For each test case, your program should output exactly Q lines, the sum of the distinct number in all substrings of length w for each query.
 

Sample Input

7 1 1 2 3 4 4 5 3 1 2 3 0
 

Sample Output

7 10 12
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值