题目来源:洛谷 3128
思路:
首先做lca,找到lca以后进行点的标记,开始的位置和结束的位置+1,lca -1,lca的父节点-1,然后做树上差分,顺便记录答案即可。
代码:
#include <bits/stdc++.h>
#define pii pair<int,int>
#define mp(a,b) make_pair(a,b)
#define fi first
#define se second
using namespace std;
const int maxn = 50010;
int _first[maxn], _to[maxn<<1], _next[maxn<<1], cnt;
int up[maxn][25], deep[maxn], son[maxn], p, mx, val[maxn];
bool vis[maxn];
priority_queue <pii> q1;
void add(int a, int b){
_next[++cnt] = _first[a];
_first[a] = cnt;
_to[cnt] = b;
}
void dfs(int now){
for(int i = 1; i <= 20; i ++)
up[now][i] = up[up[now][i-1]][i-1];
bool ok = 0;
for(int i = _first[now]; i; i = _next[i])
if(_to[i] != up[now][0])
up[_to[i]][0] = now, deep[_to[i]] = deep[now] + 1, dfs(_to[i]), ok = 1;
if(!ok) son[++p] = now;
return;
}
void calc(){
for(int i = 1; i <= p; i ++)
q1.push(mp(deep[son[i]], son[i])), vis[son[i]] = 1;
while(!q1.empty()){
pii t = q1.top();
q1.pop();
vis[t.se] = 0;
val[up[t.se][0]] += val[t.se];
mx = max(mx, val[up[t.se][0]]);
if(up[t.se][0] && !vis[up[t.se][0]]) q1.push(mp(deep[up[t.se][0]], up[t.se][0])), vis[up[t.se][0]] = 1;
}
}
int lca(int a, int b){
if(a == b) return a;
if(deep[a] < deep[b]) swap(a, b);
if(deep[a] != deep[b])
for(int i = 20; i >= 0; i --)
if(deep[up[a][i]] >= deep[b]) a = up[a][i];
if(a == b) return a;
for(int i = 20; i >= 0; i --)
if(up[a][i] != up[b][i]) a = up[a][i], b = up[b][i];
return up[a][0];
}
int main(){
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i < n; i ++){
int a, b;
scanf("%d%d", &a, &b);
add(a,b), add(b,a);
}
deep[1] = 1;
dfs(1);
for(int i = 1; i <= m; i ++){
int a, b;
scanf("%d%d", &a, &b);
val[a] += 1;
val[b] += 1;
int t = lca(a,b);
val[t] -= 1;
val[up[t][0]] -= 1;
}
calc();
printf("%d", mx);
return 0;
}