CF193D Two Segments 题解
toolong114514 · · 题解
2025 年/回归文化课后第一篇题解。
解题思路
注意到公差为
那么有两种思路:枚举原序列上这两个区间、枚举只有一段的连续整数区间(值域)。后一种显然更有前途。
考虑从小到大枚举值域区间的右端点,并维护对于当前的右端点,每一个左端点构成的值域区间,在映射到原序列上能划分的最小段数(简称划分段数),查找段数
枚举右端点已经是
记当前的右端点为
我们假设对于所有值域区间,新加入的这一点与它在原序列上映射的区间全部不相邻,所以先给所有的值域区间的划分段数
注意到对于区间
注意到对于区间
还注意到只有划分段数
时间复杂度
参考代码
#include<algorithm>
#include<iostream>
using namespace std;
#define int long long
const int N=3e5+10;
struct ccf{
int l,r,laz,min1,min2,cnt1,cnt2;
}tree[4*N];
void build(int pos,int lft,int rgt){
tree[pos].l=lft;
tree[pos].r=rgt;
tree[pos].min2=N;
tree[pos].cnt1=rgt-lft+1;
if(lft==rgt) return;
int mid=(lft+rgt)/2;
build(pos*2,lft,mid);
build(pos*2+1,mid+1,rgt);
}
void push_up(int pos){
tree[pos].cnt1=tree[pos].cnt2=0;
tree[pos].min2=N;
tree[pos].min1=min(tree[pos*2].min1,tree[pos*2+1].min1);
if(tree[pos].min1==tree[pos*2].min1) tree[pos].cnt1+=tree[pos*2].cnt1;
else tree[pos].min2=min(tree[pos].min2,tree[pos*2].min1);
if(tree[pos].min1==tree[pos*2+1].min1) tree[pos].cnt1+=tree[pos*2+1].cnt1;
else tree[pos].min2=min(tree[pos].min2,tree[pos*2+1].min1);
tree[pos].min2=min(tree[pos].min2,min(tree[pos*2].min2,tree[pos*2+1].min2));
if(tree[pos].min2==tree[pos*2].min1) tree[pos].cnt2+=tree[pos*2].cnt1;
if(tree[pos].min2==tree[pos*2+1].min1) tree[pos].cnt2+=tree[pos*2+1].cnt1;
if(tree[pos].min2==tree[pos*2].min2) tree[pos].cnt2+=tree[pos*2].cnt2;
if(tree[pos].min2==tree[pos*2+1].min2) tree[pos].cnt2+=tree[pos*2+1].cnt2;
}
void push_down(int pos){
tree[pos*2].min1+=tree[pos].laz,tree[pos*2].min2+=tree[pos].laz;
tree[pos*2+1].min1+=tree[pos].laz,tree[pos*2+1].min2+=tree[pos].laz;
tree[pos*2].laz+=tree[pos].laz,tree[pos*2+1].laz+=tree[pos].laz;
tree[pos].laz=0;
}
void upd(int pos,int lft,int rgt,int x){
if(lft>rgt||tree[pos].r<lft||rgt<tree[pos].l) return;
if(lft<=tree[pos].l&&tree[pos].r<=rgt){
tree[pos].min1+=x,tree[pos].min2+=x,tree[pos].laz+=x;
return;
}
push_down(pos);
upd(pos*2,lft,rgt,x);
upd(pos*2+1,lft,rgt,x);
push_up(pos);
}
int ask(int pos,int lft,int rgt){
if(tree[pos].r<lft||rgt<tree[pos].l) return 0;
if(lft<=tree[pos].l&&tree[pos].r<=rgt){
int tmp=0;
if(tree[pos].min1<=2) tmp+=tree[pos].cnt1;
if(tree[pos].min2<=2) tmp+=tree[pos].cnt2;
return tmp;
}
push_down(pos);
return ask(pos*2,lft,rgt)+ask(pos*2+1,lft,rgt);
}
int a[N],b[N];
int n,ans;
signed main(){
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
b[a[i]]=i;
}
build(1,1,n);
for(int i=1;i<=n;i++){
int ll=b[i]-1,rr=b[i]+1;
upd(1,1,i,1);
if(a[ll]<i) upd(1,1,a[ll],-1);
if(a[rr]<i) upd(1,1,a[rr],-1);
ans+=ask(1,1,i-1);
}
cout<<ans;
return 0;
}
CF 通过记录
Written by toolong114514 on 2025/1/19.