Substrings
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 183 Accepted Submission(s): 42
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
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
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
个人收获一点:使用 long long 型的时候,最好不要用printf的%lld,容易出错,用cout输出比较保险
AC代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
int n, q;
int A[1000100], B[1000100], C[1000100], num[1000100], mark[1000100];
long long dp[1000100];
void init() {
//初始化A数组,表示长度为i时,最后一个串中有多少个不同数;
memset(mark, -1, sizeof(mark));
A[1] = 0;
for(int i = 2; i <= n; i++) {
A[i] = A[i-1];
if(mark[num[n-i+1]] == -1) {
A[i]++;
mark[num[n-i+1]] = 1;
}
}
//初始化B数组,表示最近距离为i的相同数字的个数;
memset(mark, -1, sizeof(mark));
memset(B, 0 , sizeof(B));
for(int i = 0; i < n; i++) {
if(mark[num[i]] == -1) {
mark[num[i]] = i; //num[i]这个值上一次出现是在i位置
B[i+1] ++;
}
else {
B[i-mark[num[i]]] ++;
mark[num[i]] = i;
}
}
}
void solve() {
init();
int sum;
dp[1] = sum = n;
for(int i = 2; i <= n; i++) {
sum -= B[i-1];
dp[i] = dp[i-1] - A[i] + sum;
}
}
int main() {
while(scanf("%d", &n), n != 0) {
for(int i = 0; i < n; i++)
scanf("%d", &num[i]);
scanf("%d", &q);
solve();
while(q--) {
int l;
scanf("%d", &l);
cout<<dp[l]<<endl;
}
}
return 0;
}