CSES - Shared codeLink to this code:
https://cses.fi/paste/0f766a77090c876781978d/
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
//typedef __int128 lll;
#define PI 3.14159265358979323846
#define sbits(x) __builtin_popcount(x)
#define tbits(total_size , num) total_size - __builtin_clz(num)
#define pb push_back
#define f first
#define s second
#define clr(ds) ds.clear()
#define all(ds) ds.begin() , ds.end()
#define pi pair<ll , ll>
#define vi vector<int>
#define vll vector<ll>
#define vpi vector<pi>
#define sz(i) (int)i.size()
int xP[] = {0,0,1,-1,1,1,-1,-1} , yP[] = {1,-1,0,0,1,-1,-1,1};
using namespace std;
uint64_t time() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int rand(int a , int b){
return a + rand()%(b-a+1);
}
void setIO(string name = "") {
cin.tie(0)->sync_with_stdio(0);
if (name.size()) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
bool ckmin(auto& a , auto b){if(a<=b)return 0; else {a=b;return 1;}}
bool ckmax(auto& a , auto b){if(a>=b)return 0; else {a=b;return 1;}}
/*
_______________________________________
( If you don't fail at least 90% of the )
( time, you're not aiming high enough. )
( )
( - Alan Kay )
---------------------------------------
o ^__^
o (oo)\_______
(__)\ )\/\
||----w |
|| ||
*/
const int MAXN = 2e5;
const int MAXL = 20;
vi adj[MAXN];
int n , m;
int bin[MAXN][MAXL];
int depth[MAXN];
int mark[MAXN];
int ans[MAXN];
void build(int curr = 0 , int par = -1){
bin[curr][0] = par;
depth[curr] = (par == -1?0:depth[par]+1);
for(auto& neigh : adj[curr])if(neigh != par)
build(neigh , curr);
}
int lca(int u , int v){
int du = depth[u] , dv = depth[v];
if(du < dv)swap(du , dv) , swap(u , v);
// du is deeper than dv
int diff = du - dv;
for(int i =0 ;i<MAXL;i++)if(diff & (1<<i))
u = bin[u][i];
assert(depth[u] == depth[v]);
if(u == v)return u;
for(int i = MAXL-1;i>=0;--i)if(bin[u][i] != bin[v][i])
u = bin[u][i] , v = bin[v][i];
return bin[u][0];
}
void dfs(int curr , int par){
ans[curr] += mark[curr];
for(auto& neigh : adj[curr])if(neigh != par)
dfs(neigh , curr) , ans[curr] += ans[neigh];
}
void solve(){
cin >> n >> m;
for(int i =1 , a , b ;i<n;i++){
cin >> a >> b , --a , --b;
adj[a].pb(b);
adj[b].pb(a);
}
build();
for(int i = 1;i<MAXL;i++)for(int j=0;j<n;j++)bin[j][i] = (bin[j][i-1] == -1 ? -1 : bin[bin[j][i-1]][i-1]);
for(int i =0 ; i<m;i++){
int a , b;
cin >> a >> b,--a , --b;
int l = lca(a , b);
mark[a]++ , mark[b]++ , mark[l]--;
if(l)
mark[bin[l][0]]--;
}
dfs(0 , -1);
for(int i =0 ;i<n;i++)cout << ans[i] << " ";
cout << "\n";
}
int main(){
setIO();
int t = 1;
//cin >> t;
while(t--){
solve();
}
}