Question: 1350. Piggy banks
Ideas:
First, store the location of each key in key_positions [], and then group them with different colors starting from the first bank. For example, if the key of the first bank is in the second bank, you can open the second bank first, and the second key is in the fourth bank. You can also open the fourth bank first, and so on, until a key appears in a bank in the same group in the front, it must be broken. The visited array is initialized to 0 and marked as a color number after being accessed. Row 21st visited [cur] = color: only when the same color is found, that is, in the same group, one more key must be broken, because if the key is in another group, after solving the problem, you can naturally get the key of the group.
The pitfall is that only one group of input is required for the question, but the while (CIN> N) must be used for the test.
Code:
1 #include <iostream> 2 using namespace std; 3 4 const int MAX = 1000001; 5 int visited[MAX], key_positions[MAX]; 6 7 int main() { 8 int n; 9 while (cin >> n) {10 int result = 0, color = 1;11 for (int i = 1; i <= n; ++i) {12 cin >> key_positions[i];13 visited[i] = 0;14 }15 for (int i = 1; i <= n; ++i) {16 if (visited[i] == 0) {17 int cur = i;18 while (visited[cur] == 0) {19 visited[cur] = color;20 cur = key_positions[cur];21 if (visited[cur] == color)22 result++;23 }24 color++;25 }26 }27 cout << result << endl;28 }29 return 0;30 }