//https://codeforces.com/problemset/problem/191/C
#include<bits/stdc++.h>
#include<unordered_map>
#include<array>
#define ll long long
#define ull unsigned long long
#define all(a) a.begin(),a.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-4;
const ll mod = 998244353;
const int N = 1e5 + 50;
int n, val[N], ans[N];
vector<pair<int, int>> g[N];
struct LCA
{
int tot, fa[N], dep[N], sz[N], hson[N], top[N], dfn[N], rnk[N];
void dfs1(int x, int father, int d)
{
dep[x] = d;
hson[x] = -1;
sz[x] = 1;
for (auto [to, w] : g[x])
{
if (to == father)
continue;
fa[to] = x;
dfs1(to, x, d + 1);
sz[x] += sz[to];
if (hson[x] == -1 || sz[to] > sz[hson[x]])
hson[x] = to;
}
}
void dfs2(int x, int t)
{
top[x] = t;//所在重链的最高点t
dfn[x] = ++tot;
rnk[tot] = x;
if (hson[x] == -1)
return;
dfs2(hson[x], t);
for (auto [to, w] : g[x])
{
if (to == fa[x] || to == hson[x])
continue;
dfs2(to, to);
}
}
int lca(int x, int y)
{
int fx = top[x], fy = top[y];
while (fx != fy)
{
if (dep[fx] > dep[fy])
{
x = fa[fx];
fx = top[x];
}
else
{
y = fa[fy];
fy = top[y];
}
}
if (dep[x] > dep[y])
return y;
else
return x;
}
}L;
void dfs(int x, int fa)
{
for (auto [to, id] : g[x])
{
if (to == fa)
continue;
dfs(to, x);
ans[id] += val[to];
val[x] += val[to];
}
}
void solve()
{
cin >> n;
for (int i = 1, u, v; i < n; i++)
{
cin >> u >> v;
g[u].push_back({ v, i });
g[v].push_back({ u, i });
}
L.dfs1(1, -1, 0);
L.dfs2(1, 1);
int k;
cin >> k;
for (int i = 1, u, v; i <= k; i++)
{
cin >> u >> v;
val[u]++;
val[v]++;
val[L.lca(u, v)] -= 2;
}
dfs(1, -1);
for (int i = 1; i < n; i++)
cout << ans[i] << ' ';
}
signed main()
{
IOS;
int t = 1;
//cin >> t;
while (t--)
solve();
return 0;
}
C. Fools and Roads(树上差分板子题)
最新推荐文章于 2024-07-25 14:57:29 发布