【并查集+dfs】codeforces 1833 E. Round Dance
1.【并查集】LeetCode 721.账户合并
2.【并查集+dfs】codeforces 1833 E. Round Dance
题意
输入一个正整数
第一行,输入一个正整数
第二行,输入
这
问这
题解
建立有向边后,必定可以划分为若干张(弱)连通图,连通图若整张图就是个环且节点数大于
总结为:大二有环即为环,否则均为一条链
参考代码
#include<bits/stdc++.h> #define IOS ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); using namespace std; constexpr int N = 2e5 + 7; int T = 1, n; int a[N], in[N], dsu[N], sz[N]; bool vis[N]; int find(int x) { return x == dsu[x] ? x : dsu[x] = find(dsu[x]); } void merge(int x, int y) { int fx = find(x), fy = find(y); if (fx == fy) return ; dsu[fx] = fy; sz[fy] += sz[fx]; } void solve() { int cnt1 = 0, cnt2 = 0; cin >> n; for (int i = 1; i <= n; ++ i) { cin >> a[i]; dsu[i] = i; sz[i] = 1; in[i] = 0; vis[i] = false; } auto dfs = [&](auto &&dfs, int x) -> void { vis[x] = true; in[a[x]] ++; merge(x, a[x]); if (!vis[a[x]]) dfs(dfs, a[x]); }; unordered_map<int, bool> ump; for (int i = 1; i <= n; ++ i) if (!vis[i]) dfs(dfs, i); for (int i = 1; i <= n; ++ i) { bool b = in[i] == 2; int ro = find(i); if (ump.find(ro) == ump.end()) ump[ro] = b; else ump[ro] = b || ump[ro]; } for (auto &it: ump) (it.second || sz[it.first] < 3 ? cnt1 : cnt2) ++; cout << cnt2 + (cnt1 > 0) << ' ' << cnt1 + cnt2 << '\n'; } int main() { IOS cin >> T; while (T --) solve(); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 【.NET】调用本地 Deepseek 模型