动态开点线段树模板

结构体内不能直接初始化,否则CE

#include<bits/stdc++.h>
using namespace std;
int n,q;
int tot;
struct node{
    int l,r;
    int sum;
    int la;
}tr[15000010];
int rt;
void pull(int x){
    tr[x].sum=tr[tr[x].l].sum+tr[tr[x].r].sum;
}
void pushdown(int p,int l,int r){
    if(tr[p].la==-1)return;
    if(!tr[p].l){
        tr[tr[p].l=++tot]={0,0,0,-1};
    }
    if(!tr[p].r){
        tr[tr[p].r=++tot]={0,0,0,-1};
    }
    int mid=l+r>>1;
    tr[tr[p].l].sum=tr[p].la*(mid-l+1);
    tr[tr[p].r].sum=tr[p].la*(r-mid);
    tr[tr[p].l].la=tr[p].la;
    tr[tr[p].r].la=tr[p].la;
    tr[p].la=-1;
}
void update(int &p,int l,int r,int L,int R,int k){
    int mid= l+r>>1;
    if(!p){
        tr[p=++tot]={0,0,r-l+1,-1};
    }
    if(L<=l&& r<=R){
        k--;
        k^=1;
        tr[p].sum=k*(r-l+1);
        tr[p].la=k;
        return;
    }
    pushdown(p,l,r);
    if(L<=mid)update(tr[p].l,l,mid,L,R,k);
    if(R>mid)update(tr[p].r,mid+1,r,L,R,k);
    pull(p);
}
void solve(){
    cin>>n>>q;
    while(q--){
        int l,r,k;cin>>l>>r>>k;
        update(rt,1,n,l,r,k);
        cout<<(n-tr[rt].sum)<<endl;
    }
}

signed main()
{
  ios::sync_with_stdio(false),cin.tie(0);
  int T=1;

  while(T--){
  solve();
  }

  return 0;
}
posted @ 2025-10-24 13:42  Marinaco  阅读(5)  评论(0)    收藏  举报
//雪花飘落效果