2015
07-16

# Substrings

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

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

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

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

7
10
12

1.处理c[i]的时候，如果一个数ai前面没有相同的数，则距离计算为到0的距离i，why？因为加上这类数也是成立。

2.答案dp[i]会超int，我就wa了好几次。。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef __int64 LL;
const int maxn=1e6+10;
int c[maxn],a[maxn],pre[maxn],sum[maxn],num[maxn];
LL dp[maxn];
int main()
{
int n,m;
while(scanf("%d",&n)!=EOF)
{
if(n==0)break;
int i,j,k,t;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
memset(c,0,sizeof(c));
memset(pre,0,sizeof(pre));
for(i=1;i<=n;i++)
{
c[i-pre[a[i]]]++;//pre[a[i]]=0的也是可以的
pre[a[i]]=i;
}
sum[n]=c[n];
for(i=n-1;i>=1;i--)
sum[i]=sum[i+1]+c[i];
memset(c,0,sizeof(c));
num[1]=1;
c[a[n]]++;
for(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(i=2;i<=n;i++)
{
dp[i]=dp[i-1]-num[i-1]+sum[i];
}
//for(i=1;i<=n;i++)
//cout<<i<<":"<<num[i]<<" "<<sum[i]<<" "<<dp[i]<<endl;
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d",&t);
printf("%I64d\n",dp[t]);
}
}
return 0;
}
/*
10
1 1 2 1 2 2 3 2 1 2
1:10
2:16
3:17
4:17
5:16
6:14
7:12
8:9
9:6
10:3

*/