bocchi 题目问答 · 2024/7/23
测试案例有问题
我用最普通的并查集写,一开始没考虑相邻数才能传送,但是通过了,我感觉要加一条测试案例 5 2 1 3 5 4 代码如下 ```c++ #include<bits/stdc++.h> using namespace std; class UnionFind{ public: int n; vector<int>fa; vector<int>sz; public: UnionFind(int _n) :n(_n),fa(_n), sz(_n,1) { for (int i = 0; i < n; i++) fa[i] = i; } int f(int i) { if (fa[i] != i)fa[i]= f(fa[i]); return fa[i]; } void Union(int a, int b) { int x = f(a), y = f(b); if (x != y) { if (sz[x] > sz[y]) { fa[y] = x; sz[x] += sz[y]; sz[y] = 0; } else { fa[x] = y; sz[y] += sz[x]; sz[x] = 0; } } } void res() { sort(sz.begin(), sz.end(), [](int& a, int& b) {return a > b; }); cout << sz[0] + sz[1] << endl; } }; int main() { int n; cin >> n; vector<int>nums(n); for (int i = 0; i < n; i++) { cin >> nums[i]; nums[i]--; } UnionFind un(n); for (int i = 0; i < n; i++) { un.Union(i, nums[i]); } un.res(); return 0; } ```
查看全文
2 0 0 40