|
| 1 | +#define PROBLEM \ |
| 2 | + "https://judge.yosupo.jp/problem/frequency_table_of_tree_distance" |
| 3 | +#include "../template.hpp" |
| 4 | +#include "../cd_asserts.hpp" |
| 5 | +#include "../../../kactl/content/numerical/FastFourierTransform.h" |
| 6 | +//! @param adj unrooted, connected forest |
| 7 | +//! @returns array `num_paths` where `num_paths[i]` = # of |
| 8 | +//! paths in tree with `i` edges. `num_paths[1]` = # edges |
| 9 | +//! @time O(n log^2 n) |
| 10 | +//! @space this function allocates/returns various vectors |
| 11 | +//! which are each O(n) |
| 12 | +vector<ll> count_paths_per_length(vector<vi> adj) { |
| 13 | + vector<ll> num_paths(sz(adj)); |
| 14 | + centroid(adj, [&](int cent, int) { |
| 15 | + vector<vector<double>> child_depths; |
| 16 | + for (int v : adj[cent]) { |
| 17 | + child_depths.emplace_back(1, 0.0); |
| 18 | + for (queue<pii> q({{v, cent}}); !empty(q);) { |
| 19 | + child_depths.back().push_back(sz(q)); |
| 20 | + queue<pii> new_q; |
| 21 | + while (!empty(q)) { |
| 22 | + auto [u, p] = q.front(); |
| 23 | + q.pop(); |
| 24 | + for (int w : adj[u]) { |
| 25 | + if (w == p) continue; |
| 26 | + new_q.emplace(w, u); |
| 27 | + } |
| 28 | + } |
| 29 | + swap(q, new_q); |
| 30 | + } |
| 31 | + } |
| 32 | + sort(all(child_depths), |
| 33 | + [&](auto& x, auto& y) { return sz(x) < sz(y); }); |
| 34 | + vector total_depth(1, 1.0); |
| 35 | + for (const auto& cnt_depth : child_depths) { |
| 36 | + auto prod = conv(total_depth, cnt_depth); |
| 37 | + rep(i, 1, sz(prod)) num_paths[i] += llround(prod[i]); |
| 38 | + total_depth.resize(sz(cnt_depth)); |
| 39 | + rep(i, 1, sz(cnt_depth)) total_depth[i] += |
| 40 | + cnt_depth[i]; |
| 41 | + } |
| 42 | + }); |
| 43 | + return num_paths; |
| 44 | +} |
| 45 | +int main() { |
| 46 | + cin.tie(0)->sync_with_stdio(0); |
| 47 | + int n; |
| 48 | + cin >> n; |
| 49 | + vector<vector<int>> adj(n); |
| 50 | + for (int i = 0; i < n - 1; i++) { |
| 51 | + int u, v; |
| 52 | + cin >> u >> v; |
| 53 | + adj[u].push_back(v); |
| 54 | + adj[v].push_back(u); |
| 55 | + } |
| 56 | + cd_asserts(adj); |
| 57 | + vector<ll> cnt_len = count_paths_per_length(adj); |
| 58 | + for (int i = 1; i < n; i++) cout << cnt_len[i] << " "; |
| 59 | + cout << '\n'; |
| 60 | + return 0; |
| 61 | +} |
0 commit comments