尺取法,先右挪右端点,可以了就挪左端点至不行,然后又挪右端点,一直一直一直这样子
#include<iostream> #include<cstdio> #define ri register int #define u int namespace opt { inline u in() { u x(0),f(1); char s(getchar()); while(s<'0'||s>'9') { if(s=='-') f=-1; s=getchar(); } while(s>='0'&&s<='9') { x=(x<<1)+(x<<3)+s-'0'; s=getchar(); } return x*f; } } using opt::in; #define NN 1000005 namespace mainstay { u N,M,cnt,ans[3]={0x7fffffff},vt[NN],a[NN]; inline void solve(){ N=in(),M=in(); for(ri i(1);i<=N;++i) a[i]=in(); u l(1),r(0); while(1){ if(l>=N||r>=N) break; if(!vt[a[r+1]]) ++cnt; ++vt[a[++r]]; while(cnt==M){ if(r-l+1<ans[0]){ ans[0]=r-l+1,ans[1]=l,ans[2]=r; } --vt[a[l++]]; if(!vt[a[l-1]]) --cnt; } } std::cout<<ans[1]<<" "<<ans[2]; } } int main() { //freopen("x.txt","r",stdin); std::ios::sync_with_stdio(false); mainstay::solve(); }