CF190 D. Non-Secret Cypher

CF190 D. Non-Secret Cypher

Question

給定一個長度爲nn求滿足[L,R][L,R]中有至少kk個數字相同的子區間的數量。
1kn4×1051\le k\le n \le 4\times 10^5

Solution

遇到這種和[L,R][L,R]有關的子區間數量問題,可以採取尺取法,尺取法每個邊界判斷一組,複雜度爲O(2N)O(2N)O(N)O(N),我們在尺取邊界的同時,計入當前邊界所能增加的貢獻值即可。
[L,R][L,R]固定時,每次加上nR+1n-R+1,因爲[L,r][L,r]r[R,N]r\in [R,N]時都滿足。

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章