VJ的链接:https://cn.vjudge.net/problem/Gym-101908L
题目大意:
一棵\(n\)个点的树上,查询\(a\) ~ \(b\),\(c\) ~ \(d\)两段路径公共的点的个数。
解题思路:
读完题就感觉是树链剖分的裸题呀...
树链剖分可以在\(O(logN)\)的时间内维护树上任意一条路径上的点权之和
把每个点的权值初始化为\(0\),对于每次询问,把\(a\) ~ \(b\)这条路径的值\(+1\),查询\(c\) ~ \(d\)的区间和,再把\(a\) ~ \(b\)这条路径的值\(-1\)改回来。\(c\) ~ \(d\)的区间和就是交点数量。
代码:
(就是树链剖分维护点权的模板,改了下main就过了...)
#include
#include
#include
using namespace std;
const int maxn = 100000+10;
int w[maxn];
int N, Q;
struct
{
int to,next;
}e[maxn<<1];
int head[maxn],edgeNum;
void add(int u,int v)
{
e[edgeNum].next = head[u];
e[edgeNum].to = v;
head[u] = edgeNum++;
}
/*-------------------------树剖------------------------------*/
int deep[maxn],fa[maxn],siz[maxn],son[maxn];
void dfs1(int u,int pre,int d)
{
deep[u] = d;
fa[u] = pre;
siz[u] = 1;
son[u] = 0;
for(int i=head[u];~i;i=e[i].next)
{
int v = e[i].to;
if(v!=pre)
{
dfs1(v,u,d+1);
siz[u] += siz[v];
if(siz[v]>siz[son[u]])
son[u] = v;
}
}
}
int top[maxn],id[maxn],rk[maxn],cnt;
int &n = cnt;
void dfs2(int u,int t)
{
top[u] = t;
id[u] = ++cnt;
rk[cnt] = u;
if(!son[u]) return;
dfs2(son[u],t);
for(int i=head[u];~i;i=e[i].next)
{
int v = e[i].to;
if(v!=son[u]&&v!=fa[u])
dfs2(v,v);
}
}
/*-------------------------树剖------------------------------*/
/*-------------------------线段树------------------------------*/
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int sum[maxn<<2],lazy[maxn<<2];
void pushup(int rt)
{
sum[rt] = (sum[rt<<1] + sum[rt<<1|1]);
}
void build(int l,int r,int rt)
{
if(l==r)
{
sum[rt] = w[rk[l]];
return ;
}
int m = l+r>>1;
build(lson);
build(rson);
pushup(rt);
}
void pushdown(int rt,int l,int r)
{
if(lazy[rt])
{
lazy[rt<<1] = (lazy[rt<<1] + lazy[rt]);
lazy[rt<<1|1] = (lazy[rt<<1|1] + lazy[rt]);
sum[rt<<1] += (lazy[rt] * l);
sum[rt<<1|1] += (lazy[rt] * r);
lazy[rt] = 0;
}
}
void update(int L,int R,int val,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
sum[rt] = (sum[rt] + (val) * ((r-l+1)));
lazy[rt] += val;
return ;
}
int m = l + r >> 1;
pushdown(rt,m-l+1,r-m);
if(L<=m)
update(L,R,val,lson);
if(R>m)
update(L,R,val,rson);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return sum[rt];
int m = l + r >> 1,ans = 0;
pushdown(rt,m-l+1,r-m);
if(L<=m)
ans = (ans + query(L,R,lson));
if(R>m)
ans = (ans + query(L,R,rson));
return ans;
}
/*-------------------------线段树------------------------------*/
/*-----------------------树剖加线段树--------------------------*/
void update(int x,int y,int z)
{
while(top[x]!=top[y])
{
if(deep[top[x]]deep[y])
swap(x,y);
update(id[x],id[y],z,1,n,1);
}
int query(int x,int y)
{
int ans = 0;
while(top[x] != top[y])
{
if(deep[top[x]] < deep[top[y]])
swap(x,y);
ans = (ans + query(id[top[x]],id[x],1,n,1));
x = fa[top[x]];
}
if(deep[x]>deep[y])
swap(x,y);
ans = (ans + query(id[x],id[y],1,n,1));
return ans;
}
/*-----------------------树剖加线段树--------------------------*/
void init()
{
memset(head,-1,4*N+4);
cnt = edgeNum = 0;
}
int u, v, x1, y1, x2, y2;
int main()
{
scanf("%d%d",&N,&Q);
init();
for(int i=1;i