题目链接:http://codeforces.com/contest/755/problem/C
题意:
有 n 个组成了几个森林,已知 p[i] 是第 i 个节点到其它节点的最长的距离。求有多少个森林。
题解:
可以直接用并查集水,无意间发现了 tourist 的解法,觉得挺好,与大家分享一下。
他的思路是:
1:如果这个点最长的距离是到他自己的距离,那么他肯定是单独组成了一个森林,个数统计在 变量 cnt 中。
2:否则将这个节点存到 set 中。(set 可以自动去重)
最后用 cnt + [set.size()/2] 就是答案。
并查集代码就不贴了,附上用 tourist 的方法写的代码:
#include <set>
#include <cstdio>
using namespace std;
int main(){
#ifdef _Isopen_File_
freopen(".in","r",stdin);
// freopen(".out","w",stdout);
#endif
#ifdef _Is_Close_STD_
ios::sync_with_stdio(false);
cin.tie(0);
#endif
set<int> uniq;
int n, ans = 0;
scanf("%d", &n);
for ( int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
if(x == i) {
ans ++;
} else uniq.insert(x);
}
printf("%d\n", ans + uniq.size()/2);
return 0;
}