链接
树上差分的点模板,只需记住两个点各自加1,公共祖先减一,公共祖先的父亲减一.还原是对子树求和,记住这些即可
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
const int INF = 1e9+7;
typedef long long ll;
typedef pair<int,int> pii;
#define all(a) (a).begin(), (a).end()
#define pb(a) push_back(a)
vector<int> G[maxn];
//前向星
// for(int i=head[u];i!=-1;i=nxt[i]) v = to[i]
//int nxt[maxn],head[maxn],to[maxn];// head[u],cnt 初始值是-1
//int tot = -1;
//void add(int u,int v){
// nxt[++tot] = head[u];
// head[u] = tot;
// to[tot] = v;
//}
int fa[maxn][31];int depth[maxn];
void dfs1(int u,int f){
fa[u][0]=f;depth[u] = depth[f] +1;
for(int i=1;i<=__lg(depth[u]);i++){
fa[u][i] = fa[fa[u][i-1]][i-1];
}
for(auto v :G[u]){
if(v!=f) dfs1(v,u);
}
}
int lca(int u,int v){
if(depth[u]<depth[v]) swap(u,v);
while(depth[u]!=depth[v]) u = fa[u][__lg(depth[u]-depth[v])];
if(u==v) return u;
for(int i=__lg(depth[u]);i>=0;i--){
if(fa[u][i]!=fa[v][i]) u=fa[u][i],v=fa[v][i];
}
return fa[u][0];
}
int diff[maxn];int sum[maxn];
void dfs(int u,int f){
sum[u] = diff[u];
for(auto v : G[u]){
if(v!=f){
dfs(v,u);sum[u]+=sum[v];
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n,m;cin>>n>>m;
for(int i=1;i<=n-1;i++){
int u,v;cin>>u>>v;
G[u].pb(v);G[v].pb(u);
}
dfs1(1,0);
while(m--){
int u,v;cin>>u>>v;
diff[u]++,diff[v]++;
int f1 = lca(u,v);
diff[f1]--;diff[fa[f1][0]]--;
}
int ans = 0;
dfs(1,0);
for(int i=1;i<=n;i++) ans = max(sum[i],ans);
cout<<ans;
}