Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.
The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.
Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.
Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).
The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.
The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.
Print the single number — the number of such subarrays of array a, that they have at least k equal integers.
Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.
4 2 1 2 1 2
3
5 3 1 2 1 1 3
2
3 1 1 1 1
6
In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).
In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).
In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
题意:给出n个元素的数列(n<=4e5),问有多少个子区间满足至少有一个数值出现至少K次。
解法1:
从小到大,枚举区间左端点,找对应的最左区间右端点,可以发现最左区间右端点满足单调不减,所以算法的时间复杂度是O(2*n)=O(n)
#include
#include
#include
#include
#include
#include
#include
#include
解法二:
对应于解法一,枚举区间右端点,可是最右左端点并不是单调不减的。
先对所有数值离散化。记录每个值x出现了几次,并且第k次出现的位置。
右端点为i时,考虑求其最右左端点R[i](假设存在),
如果a[i]的值为x,现在x出现了m次,考虑第m-K+1个x出现的位置pos。
如果R[i-1]存在,那么R[i]=max(R[i-1],pos);
ans=∑(R[i])
#include
#include
#include
#include
#include
#include
#include
#include