File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` cpp
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+
5+ int N;
6+ vector<vector<int >> v (200001);
7+ int dep[ 200001] {};
8+ int par[ 200001] [ 18 ] {}, dist[ 200001] [ 18 ] {};
9+
10+ void dfs(int n, int p, int d) {
11+ dep[ n] = d, par[ n] [ 0 ] = p;
12+ for(int i: v [ n] ) if(i != p) {
13+ dfs(i,n,d+1);
14+ dist[ i] [ 0 ] = 1;
15+ }
16+ }
17+
18+ int main() {
19+ cin.tie(0)->sync_with_stdio(0);
20+
21+ cin>>N;
22+ for(int i=1,a,b;i<N;i++){
23+ cin>>a>>b;
24+ v[ a] .push_back(b);
25+ v[ b] .push_back(a);
26+ }
27+
28+ dfs(1,0,0);
29+ for(int k=1;k<18;k++) for(int i=1;i<=N;i++) {
30+ par[ i] [ k ] = par[ par[ i] [ k-1 ]] [ k-1 ] ;
31+ dist[ i] [ k ] = dist[ i] [ k-1 ] + dist[ par[ i] [ k-1 ]] [ k-1 ] ;
32+ }
33+
34+ long long ans = 0;
35+ for(int i=1;i<=N;i++) for(int j=i* 2;j<=N;j+=i) {
36+ int a = i, b = j, diff = abs(dep[ a] - dep[ b] );
37+
38+ for(int k=0;k<18;k++) if(diff & (1<<k)) {
39+ if(dep[ a] > dep[ b] ) swap(a,b);
40+ ans += dist[ b] [ k ] ;
41+ b = par[ b] [ k ] ;
42+ }
43+
44+ for(int k=17;k>=0;k--) if(par[ a] [ k ] != par[ b] [ k ] ) {
45+ ans += dist[ a] [ k ] + dist[ b] [ k ] ;
46+ a = par[ a] [ k ] ;
47+ b = par[ b] [ k ] ;
48+ }
49+ if(a != b) {
50+ ans += 2;
51+ }
52+ ans++;
53+ }
54+
55+ cout<<ans;
56+
57+ }
58+ ```
You can’t perform that action at this time.
0 commit comments