I try to use heavy path decomposition to ask LCA
but I found the code run slowly particularly in the condition of chain
What going on? What wrong with my heavy path decomposition?
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define debug cout<<-1<<endl
const int maxn=2e5+5;
int n,m;
int a,b;
int uu,vv;
int siz[maxn];
int dep[maxn];
int top[maxn];
int son[maxn];
int vis[maxn];
int fa[maxn];
vector<int>q[maxn];
int maxx=0;
struct node{
int l,r,lca;
}nod[maxn];
bool cmp(node a,node b){
return dep[a.lca]>dep[b.lca];
}
void dfs1(int u,int last){
dep[u]=dep[fa[u]]+1;
siz[u]=1;
for(int i=0;i<q[u].size();i++){
int v=q[u][i];
if(v!=fa[u]){
fa[v]=u;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>maxx) {
son[u]=v;
maxx=siz[v];
}
}
}
}
void dfs2(int u,int tp){
top[u]=tp;
if(son[u]){
dfs2(son[u],tp);
}
for(int i=0;i<q[u].size();i++){
int v=q[u][i];
if(v==son[u]||v==fa[u]){
continue;
}
dfs2(v,v);
}
}
void dfs3(int u,int last){
vis[u]=1;
for(int i=0;i<q[u].size();i++){
int v=q[u][i];
if(v!=fa[u]){
dfs3(v,u);
}
}
}
int lca(int a,int b){
while(top[b]!=top[a]){
if(dep[a]>dep[b]){
swap(a,b);//depa <depb
}
b=fa[top[b]];
}
if(dep[a]>dep[b]){
swap(a,b);//depa <depb
}
return a;
}
signed main(){
freopen("paths.in","r",stdin);
freopen("paths.out","w",stdout);
scanf("%lld%lld",&n,&m);
int opt=0;
for(int i=1;i<=n-1;i++){
scanf("%lld%lld",&a,&b);
q[a].push_back(b);
q[b].push_back(a);
}
dfs1(1,0);
dfs2(1,1);
fa[1]=1;
for(int i=1;i<=m;i++){
scanf("%lld%lld",&uu,&vv);
nod[i].l=uu;
nod[i].r=vv;
nod[i].lca=lca(uu,vv);
}
sort(nod+1,nod+m+1,cmp);
int ans=0;
for(int i=1;i<=m;i++){
if(!vis[nod[i].l]&&!vis[nod[i].r]&&!vis[nod[i].lca]){
dfs3(nod[i].lca,fa[nod[i].lca]);
ans++;
}
}
cout<<ans<<endl;
}