OI模板合集(数据结构、图论、数论)

niushao 2020-02-10

本模板合集将持续更新

数据结构

  • 并查集
    编写次数:29
int fa[MAX];
int find(int x){
    return x==fa[x]?x:fa[x]=find(fa[x]);
}
inline void merge(int x,int y){
    register int a=find(x),b=find(y);
    if(a!=b)fa[a]=b;
}
int main(){
    for(register int i=1;i<=n;++i)fa[i]=i;
    return 0;
}
  • 树状数组 BIT
    编写次数:24
int Arr[MAX];
inline void Add(int x,int v){
    while(x<=n){
        Arr[x]+=v;
        x+=(x&-x);
    }
}
inline int Query(int x){
    register int res=0;
    while(x){
        res+=Arr[x];
        x+=(x&-x);
    }
    return res;
}
  • 线段树 seg
    编写次数:25
int tree[MAX<<2],tag[MAX<<2];
inline void pushup(int x){
    tree[x]=tree[x<<1]+tree[x<<1|1];
}
inline void push_down(int x,int l,int r,int v){
    tag[x]+=v;tree[x]+=(r-l+1)*v; 
}
inline void pushdown(int x,int l,int r){
    register int mid=l+r>>1;
    push_down(x<<1,l,mid,tag[x]);
    push_down(x<<1|1,mid+1,r,tag[x]);
    tag[x]=0;
}
int query(int x,int l,int r,int s,int t){
    if(s<=l&&r<=t)return tree[x]; 
    register int res=0,mid=l+r>>1; 
    pushdown(x,l,r);
    if(s<=mid)res+=query(x<<1,l,mid,s,t);
    if(mid<t)res+=query(x<<1|1,mid+1,r,s,t);
    return res;
}
void modify(int x,int l,int r,int s,int t,int v){
    if(s<=l&&r<=t){
        tag[x]+=v;
        tree[x]+=(r-l+1)*v;
        return ;
    }
    pushdown(x,l,r);
    register int mid=l+r>>1;
    if(s<=mid)modify(x<<1,l,mid,s,t,v);
    if(mid<t)modify(x<<1|1,mid+1,r,s,t,v);
    pushup(x);
}
int a[MAX];
void build(int x,int l,int r){
    if(l==r){
        tree[x]=a[l];
        return ;
    }
    register int mid=l+r>>1;
    build(x<<1,l,mid);
    build(x<<1|1,mid+1,r);
    pushup(x);
}

相关推荐