题意:求出包含所有出现过的元素的子段有多少个
思路:用双指针算法维护两个指针中有多少种类的元素,如果包含全部元素则直接计算答案
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 1e5 + 10;
int a[N], cnt[N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)cin >> a[i];
a[n + 1] = 0;
cnt[0] = 1;
int res = 0;
int num = 0;
for (int i = 1, j = 1; i <= n;) {
while (j <= n && num != m) {
if (cnt[a[j]] == 0)num++;
cnt[a[j]]++;
j++;
}
if(num==m)res += n - j + 2;
cnt[a[i]]--;
if (cnt[a[i]] == 0)num--;
i++;
}
cout << res << endl;
}