Each connected block is smashed open one can get all the money, so use and check set to find the number of connected blocks
-------------------------------------------------------------------
#include <bits/stdc++.h>#define REP (i, n) for (int i = 0; i < n; i++)#define CLR (x, C) memset (x, C, sizeof (x))using namespace std;const int MAXN = 1000009;int FA[MAXN], n, ans; int find (int x) {return x = = Fa[x]? x:fa[x] = Find (fa[x]);}void Unite (int x, int y) {int a = find (x), B = Find (y);Fa[a] = b;ans-= a! = B;}int main () {freopen ("test.in", "R", stdin);cin >> N;ans = n;Rep (i, n) fa[i] = i;Rep (i, N) {int v;scanf ("%d", &v);Unite (--V, i);}cout << ans << "\ n";return 0;}
-------------------------------------------------------------------
1529: [Poi2005]ska Piggy Banks Time Limit:5 Sec Memory Limit:MB
Submit:959 Solved:437
[Submit] [Status] [Discuss] Descriptionbyteazar has N Piggy piggy banks. Each piggy bank can only be opened with a key or smashed open. Byteazar has put the keys to each piggy bank in some piggy banks. Byteazar now wants to buy a car so he has to take all the money out. He wanted to break the piggy bank and take out all the money and ask at least how many piggy banks to break. Input first line an integer n (1 <= N <= 1.000.000) – Represents the total number of piggy banks. Next each line is an integer, and the integer of line i+1 represents the piggy bank number that the key of the deposit jar is placed on. Output An integer that indicates the minimum number of piggy banks to break. Sample Input 4
2
1
2
4
Sample Output
2
In the foregoing example piggy Banks 1 and 4 has to be smashed.HINT
Source
Bzoj 1529: [Poi2005]ska Piggy Banks (and set)