#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#define ls (x<<1)
#define rs (x<<1|1)
#define N 300010
#define M 8000010
#define LL long long
using namespace std;
int n,cnt=0,tot=0;
int dfn[N],dep[N],nxt[2*N],to[2*N],d[N],sz[N],son[N],fa[N],tp[N];
int size[M],lazy[M],sum[M];
inline int read()
{
int s=0,k=1;
char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if(ch=='-') k=-1,ch=getchar();
while(ch>='0'&&ch<='9') s=s*10+(ch-'0'),ch=getchar();
return s*k;
}
inline void add(int x,int y)
{
to[++cnt]=y;nxt[cnt]=d[x];d[x]=cnt;
}
inline void build(LL x,LL l,LL r)
{
size[x]=r-l+1;//if(x==2)cout<<size[2]<<' '<<r<<' '<<l<<" "<<'$'<<' ';
if(l==r) {sum[x]=0;return;}
LL mid=(l+r)>>1;
build(ls,l,mid);build(rs,mid+1,r);
sum[x]=sum[ls]+sum[rs];
}
inline void down(LL x)
{
sum[ls]+=lazy[x]*size[ls];
sum[rs]+=lazy[x]*size[rs];
lazy[ls]+=lazy[x];
lazy[rs]+=lazy[x];
lazy[x]=0;
}
inline void update(LL x,LL l,LL r,LL xl,LL xr,LL num)
{
if(l!=r) down(x);
if(l==xl&&xr==r)
{
sum[x]+=num*size[x];//cout<<sum[2]<<'&'<<size[2]<<" "<<" ";
lazy[x]+=num;
return;
}
LL mid=(l+r)>>1;
if(xr<=mid) update(ls,l,mid,xl,xr,num);
else if(xl>mid) update(rs,mid+1,r,xl,xr,num);
else update(ls,l,mid,xl,mid,num),update(rs,mid+1,r,mid+1,xr,num);
sum[x]=sum[ls]+sum[rs];
}
inline LL query(LL x,LL l,LL r,LL xl,LL xr)
{
if(l!=r) down(x);
if(xl<=l&&r<=xr) {return sum[x];}
LL mid=(l+r)>>1;
if(xr<=mid) return query(ls,l,mid,xl,xr);
else if(xl>mid) return query(rs,mid+1,r,xl,xr);
else return query(ls,l,mid,xl,mid)+query(rs,mid+1,r,mid+1,xr);
}
inline void dfs1(LL x,LL depth)
{
dep[x]=depth;
sz[x]=1;
for(LL i=d[x];i;i=nxt[i])
{
LL now_to=to[i];
if(!dep[now_to])
{
fa[now_to]=x;
dfs1(now_to,depth+1);
sz[x]+=sz[now_to];
if(sz[now_to]>sz[son[x]]) son[x]=now_to;//找重儿子
}
}
}
inline void dfs2(LL x,LL boss)
{
dfn[x]=++tot;
tp[x]=boss;
if(son[x]) dfs2(son[x],boss);
for(LL i=d[x];i;i=nxt[i])
{
LL now_to=to[i];
if(now_to!=son[x]&now_to!=fa[x]) dfs2(now_to,now_to);
}
}
inline void LCA1(LL x,LL y)
{
while(tp[x]!=tp[y])
{
if(dep[tp[x]]<dep[tp[y]]) swap(x,y);
update(1,1,n,dfn[tp[x]],dfn[x],1);
x=fa[tp[x]];
}
if(dep[x]>dep[y]) swap(x,y);
update(1,1,n,dfn[x],dfn[y],1);
}
inline LL LCA2(LL x,LL y)
{
LL ret=0;
while(tp[x]!=tp[y])
{
if(dep[tp[x]]<dep[tp[y]]) swap(x,y);
ret+=query(1,1,n,dfn[tp[x]],dfn[x]); //cout<<dfn[tp[x]]<<" "<<dfn[x]<<" "<<ret<<endl;
x=fa[tp[x]];
}
if(dfn[x]>dfn[y]) swap(x,y);
ret+=query(1,1,n,dfn[x],dfn[y]);//cout<<dfn[tp[x]]<<' '<<dfn[x]<<' '<<ret<<endl;
return ret;
}
/*inline LL LCA(LL x,LL y)
{
while(tp[x]!=tp[y])
{
if(dfn[tp[x]]<dfn[tp[y]]) swap(x,y);
x=fa[tp[x]];
}
if(dfn[x]>dfn[y]) swap(x,y);
return x;
} */
int main()
{
n=read();
for(LL i=1;i<n;i++)
{
LL x,y;
x=read();y=read();
add(x,y);
add(y,x);
}
dfs1(1,1);
dfs2(1,1);
build(1,1,n);
LL nfy=read();
while(nfy--)
{
LL x,y,z;
x=read();y=read();z=read();
if(x==1) LCA1(y,z);
else printf("%lld\n",LCA2(y,z));
}
return 0;
}
codevs4633树链剖分练习题
最新推荐文章于 2017-07-17 08:06:00 发布