1 条题解
-
0
道路设计(Road Design) 题解
思路分析
按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。
参考代码
#include <iostream> #include <vector> #include <numeric> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; if (!(cin >> n >> m)) return 0; vector<int> p(n + 1), sz(n + 1, 1); iota(p.begin(), p.end(), 0); auto find = [&](int x) { while (p[x] != x) x = p[x]; return x; }; vector<pair<int, int>> history; history.reserve(m); for (int i = 0; i < m; ++i) { int op; cin >> op; if (op == 1) { int u, v; cin >> u >> v; int ru = find(u), rv = find(v); if (ru == rv) { history.push_back({0, 0}); } else { if (sz[ru] > sz[rv]) swap(ru, rv); p[ru] = rv; sz[rv] += sz[ru]; history.push_back({ru, rv}); } } else if (op == 2) { if (!history.empty()) { auto [ru, rv] = history.back(); history.pop_back(); if (ru != 0) { p[ru] = ru; sz[rv] -= sz[ru]; } } } else { int u, v; cin >> u >> v; if (find(u) == find(v)) cout << "Yes\n"; else cout << "No\n"; } } return 0; }
- 1
信息
- ID
- 8718
- 时间
- 1500ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者