标签:www read push span ++i 细节 query else http
省选D2T3考板子可真是不多见呢。。。。~~~
这题就是一个裸的树链剖分,对于每一个Add操作,维护从u至v的路径,对于每一个Query操作,询问以u为根的子树之和。如果不会树链剖分可以看我的往期博客,具体细节在代码之中就不多赘述了~
下面给出参考代码:
#include<iostream> #include<cstdio> #define N 400005 #define M 800005 #define lc k*2 #define rc k*2+1 #define mid (l+r)/2 #define int long long using namespace std; struct node { int l,r,w,tag; }tree[4*N]; int n,m,r,p,x,y,z; int v[M],head[M],nxt[M],cnt; int dep[N],fa[N],son[N],size[N],top[N],seg[N],id; char q; int read() { int x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-48;ch=getchar();} return x*f; } void add(int a,int b) { v[++cnt]=b; nxt[cnt]=head[a]; head[a]=cnt; } void dfs1(int node,int father) { dep[node]=dep[father]+1; fa[node]=father; size[node]=1; int maxson=-1; for(int i=head[node];i;i=nxt[i]) { int go=v[i]; if(go==father)continue; dfs1(go,node); size[node]+=size[go]; if(size[go]>maxson)maxson=size[go],son[node]=go; } } void dfs2(int node,int topfather) { seg[node]=++id; top[node]=topfather; if(!son[node])return; dfs2(son[node],topfather); for(int i=head[node];i;i=nxt[i]) { int go=v[i]; if(go==fa[node]||go==son[node])continue; dfs2(go,go); } } void build(int l,int r,int k) { tree[k].l=l;tree[k].r=r; if(l==r)return; build(l,mid,lc); build(mid+1,r,rc); } void pushdown(int k) { tree[lc].tag+=tree[k].tag; tree[rc].tag+=tree[k].tag; tree[lc].w+=(tree[lc].r-tree[lc].l+1)*tree[k].tag; tree[rc].w+=(tree[rc].r-tree[rc].l+1)*tree[k].tag; tree[k].tag=0; return; } void pushup(int k) { tree[k].w=tree[lc].w+tree[rc].w; return; } void add(int x,int y,int k) { int l=tree[k].l,r=tree[k].r; if(l>=x&&r<=y) { tree[k].tag+=z; tree[k].w+=(r-l+1)*z; return; } if(tree[k].tag)pushdown(k); if(x<=mid)add(x,y,lc); if(y>mid)add(x,y,rc); pushup(k); } int query(int x,int y,int k) { int l=tree[k].l,r=tree[k].r; if(l>=x&&r<=y) { return tree[k].w; } if(tree[k].tag)pushdown(k); int res=0; if(x<=mid)res+=query(x,y,lc); if(y>mid)res+=query(x,y,rc); return res; } void Tadd(int x,int y) { while(top[x]!=top[y]) { if(dep[top[x]]<dep[top[y]])swap(x,y); add(seg[top[x]],seg[x],1); x=fa[top[x]]; } if(dep[x]>dep[y])swap(x,y); add(seg[x],seg[y],1); } int Treequery(int x) { return query(seg[x],seg[x]+size[x]-1,1); } signed main() { n=read(); for(int i=1;i<n;i++) { x=read();y=read(); x++;y++; add(x,y);add(y,x); } dfs1(1,0);dfs2(1,1); build(1,n,1); m=read(); while(m--) { cin>>q; if(q==‘A‘) { x=read();y=read();z=read(); x++;y++; Tadd(x,y); } else { x=read(); x++; cout<<Treequery(x)<<endl; } } }
标签:www read push span ++i 细节 query else http
原文地址:https://www.cnblogs.com/szmssf/p/11145035.html