1 条题解
-
0
最小公倍树(Lowest Common Tree) 题解
思路分析
按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。
参考代码
#include <iostream> #include <vector> #include <numeric> #include <algorithm> using namespace std; struct Edge { int u, v; long long w; bool operator<(const Edge& o) const { return w < o.w; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int L, R; if (!(cin >> L >> R)) return 0; int n = R - L + 1; vector<Edge> edges; for (int i = L + 1; i <= R; ++i) { edges.push_back({0, i - L, 1LL * L * i / std::gcd(L, i)}); } for (int d = 2; d <= R; ++d) { int first = ((L + d - 1) / d) * d; if (first > R) continue; for (int mult = first + d; mult <= R; mult += d) { edges.push_back({first - L, mult - L, 1LL * first / d * mult}); } } sort(edges.begin(), edges.end()); vector<int> p(n); iota(p.begin(), p.end(), 0); auto find = [&](int x) { while (p[x] != x) x = p[x] = p[p[x]]; return x; }; long long ans = 0; int cnt = 0; for (const auto& e : edges) { int ru = find(e.u), rv = find(e.v); if (ru != rv) { p[ru] = rv; ans += e.w; if (++cnt == n - 1) break; } } cout << ans << "\n"; return 0; }
- 1
信息
- ID
- 8747
- 时间
- 2000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者