Untitled
#include <bits/stdc++.h> using namespace std; typedef long long int ll; #define endl "\n" const double PI = 3.14159265358979; const ll INF = 1e18 + 7; const ll MOD = 1e9 + 7; const ll nax = 1000006; const int LOG = 25; int freq[nax]; void solve() { int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } ll ans = 0; int tail = 0, head = -1, distinct = 0; while(tail < n) { while(head + 1 < n && ((distinct + (freq[a[head + 1]] == 0)) <= k)) { head++; freq[a[head]]++; if (freq[a[head]] == 1) { distinct++; } } int length = head - tail + 1; if (length > 0) { ans += length; } if (tail <= head) { freq[a[tail]]--; if (freq[a[tail]] == 0) { distinct--; } tail++; } else { tail++; head = tail - 1; } } cout << ans << endl; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); memset(freq, 0, sizeof(freq)); int t; cin >> t; while(t--) solve(); return 0; }
Leave a Comment