codeforces 190D Non-Secret Cypher 双指针

给定长度为n的数组a,给定k,问有多少个子数组,其中至少包含着有k个相同的数字


双指针经典题目,注意先要离散,然后注意m是1的情况

#include 
#include 
#include 
#include 
#include 
#define rep(i, j, k) for(int i = j; i <= k; i++)
#define maxn 1000009
#define ll long long

using namespace std;

int n, m, a[maxn], c[maxn], now = 0, cnt = 0;
int cunt[maxn];
map  mp;
ll ans = 0;

int main ()
{
	cin >> n >> m;
	rep (i, 1, n)
		cin >> a[i], c[i] = a[i];
	sort (c + 1, c + 1 + n);
	c[0] = c[1] - 1;
	cnt = 0;
	rep (i, 1, n)
		if (c[i] != c[i - 1])
			mp[c[i]] = ++cnt;
	rep (i, 1, n)
		a[i] = mp[a[i]];
	//rep (i, 1, n) printf ("%d %d\n", i, a[i]);
	int r = 1;
	cunt[a[1]]++;
	if (m == 1)
		now++;
	rep (l, 1, n)
	{
		while (now == 0 && r < n)
		{
			r++;
			cunt[a[r]]++;
			if (cunt[a[r]] >= m)
				now++;
		}
		if (now)
			ans += 1LL * n - 1LL * r + 1LL;
		cunt[a[l]]--;
		if (cunt[a[l]] == m - 1)
			now--;
	}
	cout << ans << endl;
}


你可能感兴趣的:(Codeforces)