题意:
一棵树,有m次操作,每次给u,v图色或者查询u,v之间一共被涂了几次
思路:
树链剖分的基础题,对于每次查询和涂色,都按照正常的错做来就行了,一点一点根据链来往上爬,更新线段树即可。
错误及反思:
因为懒,有一部分代码沿用了上个题,结果疯狂TLE和WA,只能说不能偷懒啊,不过中途确实把很多东西重新想了好几遍,还是很不错的
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=201000;
pair<int,int> edge[N];
int segtree[N*4];
int lazy[N*4];
int depth[N],fa[N],son[N],top[N],si[N],id[N];
int n,tot=0,tid=0,m;
int first[N];
pair<int,int> b[N];
void addedge(int x,int y)
{
edge[tot].first=y;
edge[tot].second=first[x];
first[x]=tot++;
edge[tot].first=x;
edge[tot].second=first[y];
first[y]=tot++;
}
void dfs1(int now,int bef,int dep)
{
depth[now]=dep;
fa[now]=bef;
si[now]=1;
for(int i=first[now];i!=-1;i=edge[i].second)
{
if(edge[i].first!=bef)
{
dfs1(edge[i].first,now,dep+1);
si[now]+=si[edge[i].first];
if(son[now]==-1) son[now]=edge[i].first;
else son[now]=si[edge[i].first]>si[son[now]]?edge[i].first:son[now];
}
}
}
void dfs2(int now,int tp)
{
id[now]=tid++;
top[now]=tp;
if(son[now]!=-1) dfs2(son[now],tp);
for(int i=first[now];i!=-1;i=edge[i].second)
if(edge[i].first!=fa[now]&&edge[i].first!=son[now])
dfs2(edge[i].first,edge[i].first);
}
void pushdown(int l,int r,int rt)
{
if(lazy[rt])
{
int m=(l+r)/2;
lazy[rt<<1]+=lazy[rt];
lazy[rt<<1|1]+=lazy[rt];
segtree[rt<<1]+=lazy[rt]*(m-l+1);
segtree[rt<<1|1]+=lazy[rt]*(r-m);
lazy[rt]=0;
}
}
int cal(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
return segtree[rt];
pushdown(l,r,rt);
int m=(l+r)/2;
int ans=0;
if(L<=m) ans+=cal(L,R,lson);
if(R>m) ans+=cal(L,R,rson);
return ans;
}
int query(int L,int R)
{
int f1=top[L],f2=top[R];
int ans=0;
while(f1!=f2)
{
if(depth[f1]<depth[f2])
{
swap(f1,f2);
swap(L,R);
}
ans+=cal(id[f1],id[L],0,tid-1,1);
L=fa[f1];
f1=top[L];
}
if(L==R) return ans;
if(depth[L]>depth[R]) swap(L,R);
ans+=cal(id[son[L]],id[R],0,tid-1,1);
return ans;
}
void update(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
{
lazy[rt]++;
segtree[rt]+=r-l+1;
return ;
}
pushdown(l,r,rt);
int m=(l+r)/2;
if(L<=m) update(L,R,lson);
if(R>m) update(L,R,rson);
segtree[rt]=segtree[rt<<1],segtree[rt<<1|1];
}
void change(int L,int R)
{
int f1=top[L],f2=top[R];
while(f1!=f2)
{
if(depth[f1]<depth[f2])
{
swap(f1,f2);
swap(L,R);
}
update(id[f1],id[L],0,tid-1,1);
L=fa[f1];
f1=top[L];
}
if(L==R) return ;
if(depth[L]>depth[R]) swap(L,R);
update(id[son[L]],id[R],0,tid-1,1);
}
int main()
{
scanf("%d%d",&n,&m);
memset(son,-1,sizeof(son));
memset(first,-1,sizeof(first));
for(int i=0;i<n-1;i++)
{
scanf("%d%d",&b[i].first,&b[i].second);
addedge(b[i].first,b[i].second);
}
dfs1(1,1,1);
dfs2(1,1);
while(m--)
{
char temp[10];
int ta,tb;
scanf("%s%d%d",temp,&ta,&tb);
if(temp[0]=='P')
change(ta,tb);
else
printf("%d\n",query(ta,tb));
}
}