题意:给定一个长度为n的序列,需要找出一段最优的连续子段,使得出现在子段中出现次数为1次的数字最多(多一次少一次都不行,只要一次)。
求最优连续子段中出现次数为1次的数字个数。
首先要注意的是题目很可能读假了,什么意思呢?比如 1 2 1,我们是可以选择pos[1,3]这个区间的,只不过答案是2,也就是我们可以选择很长一段区间,里面可以有重复数字,最优解可以出现在里面,所以开始辛格的双指针是错了的。
考虑的方式从新进来的一个数的贡献算起,这个数将对前面同样出现的last[i]+1~i这个区间整体有一个+1的贡献,这时候对last[last[i]]+1~last[i]有一个-1的贡献。这么说比较抽象。
下面模拟一下:
比如 1 2 3 3 4 5 开始时
[1,1]+=1,[1,2]+=1,[1,3]+=1
反应到叶子节点是[1,1]=3,[2,2]=2,[3,3]=1
也就是当前的i到pos=3了,[1,1]表示[1,i]的答案是3
[2,2]表示[2,i]的答案是2
[3,3]表示[3,i]的答案是1
再来[4,4]+=1,[1,3]-=1
就变成了
[1,1]=2
[2,2]=1
[3,3]=0;
[4,4]=1
就是说这时候的[1,1]就是[1,pos=4]的答案
也就是 1 2 3 3区间的答案
也就是2
然后区间的这个答案满足区间的max维护
也就是说我们的线段树维护的是[区间左端点, i]的最值
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+100;
typedef long long LL;
LL last[maxn],p[maxn],a[maxn];
struct Tree{
LL l,r,sum,tag;
}tree[maxn*4];
void push_up(LL p)
{
tree[p].sum=max(tree[p*2].sum,tree[p*2+1].sum);
}
void addtag(LL p,LL d){
tree[p].sum+=d;
tree[p].tag+=d;
}
void push_down(LL p){
if(tree[p].tag!=0){
addtag(p*2,tree[p].tag);
addtag(p*2+1,tree[p].tag);
tree[p].tag=0;
}
}
void build(LL p,LL l,LL r)
{
tree[p].l=l;tree[p].r=r;tree[p].sum=0;tree[p].tag=0;
if(l==r) return;
LL mid=(l+r)>>1;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
push_up(p);
}
void modify(LL p,LL l,LL r,LL d){
if(l<=tree[p].l&&r>=tree[p].r){
addtag(p,d);
return;
}
push_down(p);
LL mid=(tree[p].l+tree[p].r)>>1;
if(l<=mid) modify(p*2,l,r,d);
if(r>mid) modify(p*2+1,l,r,d);
push_up(p);
}
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL n;cin>>n;
build(1,1,n);
LL res=1;
for(LL i=1;i<=n;i++){
cin>>a[i];
last[i]=p[a[i]];
p[a[i]]=i;
modify(1,last[i]+1,i,1);
if(last[i]) modify(1,last[last[i]]+1,last[i],-1);
res=max(res,tree[1].sum);
}
cout<<res<<endl;
return 0;
}