-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathCounting Paths.cpp
67 lines (56 loc) · 1.29 KB
/
Counting Paths.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2e5+1;
const int logN = 20;
int N, M, a, b, sub[maxN], p[maxN][logN];
int timer, in[maxN], out[maxN];
vector<int> G[maxN];
void dfs1(int u = 1, int par = 1){
in[u] = ++timer;
p[u][0] = par;
for(int i = 1; i < logN; i++)
p[u][i] = p[p[u][i-1]][i-1];
for(int v : G[u])
if(v != par)
dfs1(v, u);
out[u] = ++timer;
}
void dfs2(int u = 1){
for(int v : G[u]){
if(v != p[u][0]){
dfs2(v);
sub[u] += sub[v];
}
}
}
bool ancestor(int u, int v){
return in[u] <= in[v] && out[u] >= out[v];
}
int lca(int u, int v){
if(ancestor(u, v)) return u;
if(ancestor(v, u)) return v;
for(int i = logN-1; i >= 0; i--)
if(!ancestor(p[u][i], v))
u = p[u][i];
return p[u][0];
}
int main(){
scanf("%d %d", &N, &M);
for(int i = 0; i < N-1; i++){
scanf("%d %d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
}
dfs1();
for(int i = 0; i < M; i++){
scanf("%d %d", &a, &b);
int l = lca(a, b);
sub[a]++; sub[b]++;
sub[l]--;
if(l != 1)
sub[p[l][0]]--;
}
dfs2();
for(int i = 1; i <= N; i++)
printf("%d%c", sub[i], (" \n")[i==N]);
}