Sicily 1350. Piggy banks solution report

Source: Internet
Author: User

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 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.