4394. 最长连续子序列(acwing)

首先一看就知道是个小水题

出题人能不能准确描述 子串就是子串 什么叫连续子序列?

简而言之 找到一段颜色数量小于k且最长的子串

对每一个位置 维护一个pre数组 和endd数组

pre:在它前面离它最近的相同颜色的坐标

endd:在它后面离它最近相同颜色的坐标

初始L=R=1 不断地往后更新就好

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
#define ll long long
const int maxn=5e5+5;
int n,k,ans,LL=1,RR=1;
int a[maxn],last[maxn<<1],pre[maxn],endd[maxn];
int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		pre[i]=last[a[i]];
		last[a[i]]=i;
	}
	for(int i=0;i<=1e6;i++)last[i]=n+1;
	for(int i=n;i>=1;i--){
		endd[i]=last[a[i]];
		last[a[i]]=i;
	} 
	int L=1,R=1,res=1;
	while(R<n){
		if(pre[R+1]>=L)
			R++;
		else {
			res++;
			R++;
		}
		while(res>k){
			if(endd[L]>R){
				res--;
				L++;
			}
			else L++;
		}
		if((R-L+1)>ans){
			ans=(R-L+1);
			LL=L;RR=R;
		}
	}
	cout<<LL<<" "<<RR; 
     return 0;
}
posted @   wzx_believer  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示