建树加异或操作模拟,无了,实在是很好用,只是记录一下。 还有一个小坑,必须要把字符串转换为int类型存入
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=2e5+5;
int a[maxn],n,m;
struct node
{
int val,lazy;
}sg[maxn<<2];
void pushup(int rt)
{
sg[rt].val=sg[rt<<1].val+sg[rt<<1|1].val;
}
void build(int l,int r,int rt)
{
if(l==r)
{
sg[rt].val=a[l];return;
}
sg[rt].lazy=0;
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
pushup(rt);
}
void pushdown(int rt,int ln,int rn)
{
if(sg[rt].lazy==1)
{
sg[rt<<1].lazy^=1;
sg[rt<<1|1].lazy^=1;
sg[rt<<1].val=ln-sg[rt<<1].val;
sg[rt<<1|1].val=rn-sg[rt<<1|1].val;
sg[rt].lazy=0;
}
}
void update(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
sg[rt].val=(r-l+1)-sg[rt].val;
sg[rt].lazy^=1;
return;
}
int m=(l+r)>>1;
pushdown(rt,m-l+1,r-m);
if(L<=m) update(L,R,l,m,rt<<1);
if(R>m) update(L,R,m+1,r,rt<<1|1);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return sg[rt].val;
if(L>r||R<l)
return 0;
int m=(l+r)/2;
pushdown(rt,m-l+1,r-m);
return query(L,R,l,m,rt<<1)+query(L,R,m+1,r,rt<<1|1);
}
signed main()
{
scanf("%lld%lld",&n,&m);
string s;cin>>s;
for(int i=1;i<=n;i++)
{
if(s[i-1]=='1')
a[i]=1;
else
a[i]=0;
}
build(1,n,1);
while(m--)
{
int g,x,y;scanf("%lld%lld%lld",&g,&x,&y);
if(g==0)
{
update(x,y,1,n,1);
}
else if(g==1)
{
cout<<query(x,y,1,n,1)<<endl;
}
}
return 0;
}
https://www.luogu.com.cn/problem/P2880 线段树找区间极大值和极小值相减
#include <bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=2e5+5;
int n,m,a[maxn];
struct node
{
int val,v1=inf;
}st[maxn<<2];
void pushup(int rt)
{
st[rt].val=max(st[rt<<1].val,st[rt<<1|1].val);
st[rt].v1=min(st[rt<<1].v1,st[rt<<1|1].v1);
}
void build(int l,int r,int rt)
{
if(l==r)
{
st[rt].val=a[l];
st[rt].v1=a[l];
return;
}
int m=(l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return st[rt].val;
if(L>r||R<l)
return 0;
int mid=(l+r)>>1,ans=0;
if(L<=mid)
ans=max(ans,query(L,R,l,mid,rt<<1));
if(R>mid)
ans=max(ans,query(L,R,mid+1,r,rt<<1|1));
return ans;
}
int query1(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return st[rt].v1;
if(L>r||R<l)
return 0;
int mid=(l+r)>>1,ans=inf;
if(L<=mid)
ans=min(ans,query1(L,R,l,mid,rt<<1));
if(R>mid)
ans=min(ans,query1(L,R,mid+1,r,rt<<1|1));
return ans;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,n,1);
while(m--)
{
int x,y;scanf("%d%d",&x,&y);
cout<<query(x,y,1,n,1)-query1(x,y,1,n,1)<<endl;
}
return 0;
}
|