题解:P11012 「ALFR Round 4」B 颜料
Solution
这题明明可以做到线性怎么包括官解都写的树状数组qwq。
首先,由于选择的区间是连续的一段,而且对于每个左端点
接下来考虑每次移动指针怎么更新权值。
记
由于双指针移动时
每次
时间复杂度
代码实现中是先更新
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){
ll X = 0 ,r = 1;
char ch = getchar();
while(!isdigit(ch) && ch != '-') ch = getchar();
if(ch == '-') r = -1,ch = getchar();
while(isdigit(ch)) X = X*10+ch-'0',ch = getchar();
return X*r;
}
const int N = 2e6+10;
int n,a[N],m;
int cnt[N],sz[N];
ll k;
int main(){
n = read(); k = read();
for(int i=1;i<=n;i++) a[i] = read();
int ans = n+1;
ll res = 0;
for(int l=1,r=0;l<=n;l++){
while(r < n && res < k){
r++; sz[a[r]]++;
cnt[sz[a[r]]]++;
res += cnt[sz[a[r]]]-1;
}
if(res >= k) ans = min(ans,r-l+1);
res -= cnt[sz[a[l]]]-1;
cnt[sz[a[l]]]--; sz[a[l]]--;
}
printf("%d",ans == n+1 ? -1 : ans);
return 0;
}