CF190 D. Non-Secret Cypher
Question
給定一個長度爲求滿足中有至少個數字相同的子區間的數量。
Solution
遇到這種和有關的子區間數量問題,可以採取尺取法,尺取法每個邊界判斷一組,複雜度爲即,我們在尺取邊界的同時,計入當前邊界所能增加的貢獻值即可。
當固定時,每次加上,因爲在時都滿足。
Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const double eps = 1e-8;
const int NINF = 0xc0c0c0c0;
const int INF = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
const ll maxn = 1e6 + 5;
const int N = 4e5 +5;
int n,k,a[N];
map<int,int> M;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
int L=1,R=0;
bool ok=false;
ll ans=0;
while(R<=n){
if(ok){
ans+=n-R+1;
if(--M[a[L++]]==k-1) ok=false;
}else{
if(++M[a[++R]]==k) ok=true;
}
}
cout<<ans<<'\n';
return 0;
}