CSES - Shared codeLink to this code:
https://cses.fi/paste/24dbf4b69c9ba73c6f5e09/
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#include <bits/stdc++.h>
using namespace std;
#define files \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
#define rall(x) x.rbegin(), x.rend()
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
#define ll long long
#define rep(ii, beg, till, inc) for (int ii = beg; ii < till; ii += inc)
#define repr(ii, beg, till, inc) for (int ii = beg - 1; ii >= till; ii -= inc)
const ll MOD = 1e9 + 7;
const int MXN = 2e5 + 5;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int timer;
vector<int> graph[MXN];
int path[MXN], bad[MXN], in[MXN], out[MXN], lca[MXN][20];
void dfs(int node, int par)
{
in[node] = timer++;
lca[node][0] = par;
rep(ii, 1, 20, 1) lca[node][ii] = lca[lca[node][ii - 1]][ii - 1];
for (int child : graph[node])
if (child != par)
dfs(child, node);
out[node] = timer++;
}
int is(int u, int v)
{
return in[u] <= in[v] && out[u] >= out[v];
}
int f(int u, int v)
{
if (is(u, v))
return u;
if (is(v, u))
return v;
repr(ii, 20, 0, 1) if (!is(lca[u][ii], v)) u = lca[u][ii];
return lca[u][0];
}
int gen(int node, int par)
{
for (int child : graph[node])
if (child != par)
path[node] += gen(child, node);
path[node] -= bad[node];
return path[node] - bad[node];
}
void sol(int tc)
{
int node, p;
cin >> node >> p;
rep(ii, 1, node, 1)
{
int u, v;
cin >> u >> v;
graph[u].push_back(v);
swap(u, v);
graph[u].push_back(v);
}
dfs(1, 1);
rep(ii, 0, p, 1)
{
int u, v;
cin >> u >> v;
path[u]++;
path[v]++;
int anc = f(u, v);
bad[anc]++;
}
gen(1, 1);
rep(ii, 1, node + 1, 1) cout << path[ii] << " ";
cout << "\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T = 1;
// cin >> T;
for (int ii = 1; ii <= T; ++ii)
sol(ii);
}