Substrings
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2581 Accepted Submission(s): 798
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
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
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long long
#define N 1000000 + 10
int n, a[N], pre[N];
LL dp[N], cnt[N];
int main()
{
while(~scanf("%d", &n) && n)
{
memset(pre, 0, (n + 2) * sizeof(int));
memset(cnt, 0, (n + 2) * sizeof(int));
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
cnt[i - pre[a[i]]]++;
pre[a[i]] = i;
}
for(int i = n - 1; i >= 1; i--) cnt[i] += cnt[i + 1];
memset(pre, 0, (n + 2) * sizeof(int));
dp[1] = n;
LL num = 1;
pre[a[n]] = 1;
for(int i = 2; i <= n; i++)
{
dp[i] = dp[i - 1] + cnt[i] - num;
if(pre[a[n - i + 1]] == 0)
{
num++;
pre[a[n - i + 1]]++;
}
}
int q, w;
scanf("%d", &q);
while(q--)
{
scanf("%d", &w);
printf("%I64d\n", dp[w]);
}
}
return 0;
}