模板:树上差分
C++#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
#define int long long
const int N = 5e4 + 10,M = 30;
int n,k,c[N],ans,a[N],f[N][M],d[N],tot;
vector <int> v[N];
queue <int> q;
inline void bfs(int root)
{
d[root] = 1;
q.push(root);
while (!q.empty())
{
int x = q.front();
q.pop();
for(int i = 1;i <= tot;i ++) f[x][i] = f[f[x][i - 1]][i - 1];
for(int i = 0;i < v[x].size();i ++)
{
int g = v[x][i];
if (d[g]) continue;
d[g] = d[x] + 1;
f[g][0] = x;
q.push(g);
}
}
}
inline void dfs(int x)
{
for(int i = 0;i < v[x].size();i ++)
{
int g = v[x][i];
if (g == f[x][0]) continue;
dfs(g);
c[x] += c[g];
}
ans = max(ans,c[x]);
}
inline int lca(int x,int y)
{
if (d[x] > d[y]) swap(x,y);
for(int i = tot;i >= 0;i --)
if (d[f[y][i]] >= d[x])
y = f[y][i];
if (x == y) return y;
for(int i = tot;i >= 0;i --)
if (f[x][i] != f[y][i])
x = f[x][i],y = f[y][i];
return f[x][0];
}
signed main()
{
ios::sync_with_stdio(0);
cin >> n >> k;
tot = log2(n);
for(int i = 1;i < n;i ++)
{
int x,y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
bfs(1);
while (k --)
{
int x,y;
cin >> x >> y;
int pos = lca(x,y);
c[x] ++,c[y] ++;
c[pos] --,c[f[pos][0]] --;
}
dfs(1);
cout << ans << endl;
return 0;
}