把当前的存钱罐的祖宗变成存有他钥匙的存钱罐
#include<iostream> #include<algorithm> #include<cstring> using namespace std ; const int N = 1e6 +10 ; int n ; int s[N] ; int find(int x ){ if(x != s[x]) s[x] = find(s[x]); return s[x] ; } int main(){ cin >> n ; for(int i = 1 ; i <= n ;i ++) s[i] = i ; for(int i = 1 ; i <= n ; i++){ int x ; cin >> x ; if(find(i) != find(x)) s[i] = find(x) ; } int cnt = 0 ; for(int i = 1 ; i <= n ; i++) if(s[i] == i) cnt ++ ; cout << cnt << endl ; }