分析可知, 这里就是要砍两条边, 第一次看主要边, 第二次砍附加边, 主要边就是树边, 附加边就是非树边, 假设非树边连接为 点 x , y x,y x,y,当删除一条 x , y x,y x,y 之间的树边后, 非树边就成为了树边, 如果当 x , y x,y x,y 之间的数量为 s s s, 当 s = 0 s = 0 s=0 时, 删去任意一条非树边即可, 当 s = 1 s = 1 s=1 时, 必须要砍去x,y之间的非树边,当 s > 1 s > 1 s>1,无解
然后这里边的覆盖需要利用到区间的加减, 即差分,
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 2 * N;
int e[M], ne[M], h[N], idx, depth[N], fa[N][17], ans, n, m, d[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void bfs() //预处理
{
memset(depth, 0x3f, sizeof depth);
depth[0] = 0, depth[1] = 1;
queue<int>q;
q.push(1);
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(depth[j] > depth[t] + 1)
{
depth[j] = depth[t] + 1;
q.push(j);
fa[j][0] = t;
for(int k = 1; k <= 16; k ++ )
fa[j][k] = fa[fa[j][k - 1]][k - 1];
}
}
}
}
int lca(int a, int b) //lca模板
{
if(depth[a] < depth[b]) swap(a, b);
for(int i = 16; i >= 0; i -- )
if(depth[fa[a][i]] >= depth[b]) a = fa[a][i];
if(a == b) return a;
for(int i = 16; i >= 0; i -- )
if(fa[a][i] != fa[b][i]) a = fa[a][i], b = fa[b][i];
return fa[a][0];
}
int dfs(int u, int fa)
{
int res = d[u]; //记录当前覆盖附加边的数量
for(int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(j == fa) continue;
int s = dfs(j, u);
if(s == 0) ans += m; //该路径上没有覆盖附加边,
else if(s == 1) ans ++; // 覆盖了一条附加边
res += s; //更新附加边的数量
}
return res;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h); //初始化表头
for(int i = 1; i <= n - 1; i ++ ) //建图
{
int a, b, c;
cin >> a >> b;
add(a, b), add(b, a);
}
bfs(); //预处理 fa数组, depth数组
for(int i = 1; i <= m; i ++ )
{
int a, b;
cin >> a >> b;
d[a] ++, d[b] ++, d[lca(a, b)] -= 2; //树上差分
}
dfs(1, -1); //计算
cout << ans << '\n';
}