睡前一波树上差分
作者:
春江花月夜ovo
,
2024-05-29 23:50:41
,
所有人可见
,
阅读 20
--------传送门--------
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
vector<int> e[N];
int n, m;
int dep[N];
int ans;
int fa[N][20];
int d[N];
void bfs()
{
memset(dep, 0x3f, sizeof dep);
dep[0] = 0, dep[1] = 1;
queue<int> q;
q.push(1);
while (!q.empty())
{
auto t = q.front(); q.pop();
for (int i = 0; i < e[t].size(); i ++)
{
int j = e[t][i];
if (dep[j] > dep[t] + 1)
{
dep[j] = dep[t] + 1;
q.push(j);
fa[j][0] = t;
for (int k = 1; k <= 17; k ++)
fa[j][k] = fa[fa[j][k - 1]][k - 1];
}
}
}
}
int lca(int a, int b)
{
if (dep[a] < dep[b]) swap(a, b);
for (int i = 17; i >= 0; i --)
if (dep[fa[a][i]] >= dep[b])
a = fa[a][i];
if (a == b) return a;
for (int i = 17; 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 = 0; i < e[u].size(); i ++)
{
int j = e[u][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()
{
ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> m;
for (int i = 1; i < n; i ++)
{
int x, y;
cin >> x >> y;
e[x].push_back(y);
e[y].push_back(x);
}
bfs();
for (int i = 0; i < m; i ++)
{
int a, b;
cin >> a >> b;
int LCA = lca(a, b);
d[a] ++, d[b] ++, d[LCA] -= 2;
}
dfs(1, -1);
cout << ans << "\n";
return 0;
}
哥们你的国三比我的国三要强很多啊