HDU 4455 Substrings

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=4455


Substrings

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3115    Accepted Submission(s): 946



Problem 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 a1,a2…an, 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<=106, 0<=Q<=104, 0<= a1,a2…an <=106
 

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
 

Source

 

Recommend


思路:一个算是简单的DP题,关键在于判重。但我这个渣渣,没能单独写出来。我参考了这位大神的博客的去重方法:http://www.cnblogs.com/20143605--pcx/p/5723444.html。注意:本题极有可能超内存,STL要少用。详见代码。


附上AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1000005;
int num[maxn], len[maxn], cnt[maxn], pos[maxn];
bool vis[maxn];
ll dp[maxn];
int n, q;

int main(){
	while (~scanf("%d", &n) && n){
		memset(vis, false, sizeof(vis));
		memset(pos, 0, sizeof(pos));
		memset(cnt, 0, sizeof(cnt));
		for (int i=1; i<=n; ++i){
			scanf("%d", num+i);
			++cnt[i-pos[num[i]]];
			pos[num[i]] = i;
		}
		len[n+1] = 0;
		for (int i=n; i>=1; --i){
			if (vis[num[i]])
				len[i] = len[i+1];
			else
				len[i] = len[i+1]+1;
			vis[num[i]] = true;
		}
		dp[1] = n;
		int sum = n;
		for (int i=2; i<=n; ++i){
			dp[i] = dp[i-1]-len[n-i+2];
			sum -= cnt[i-1];
			dp[i] += sum;
		}
		scanf("%d", &q);
		while (q--){
			scanf("%d", &sum);
			printf("%I64d\n", dp[sum]);
		}
	}
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值