755C.md (2489B)
1 Source: https://codeforces.com/problemset/problem/755/C 2 3 C. PolandBall and Forest 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with *k* vertices and *k* - 1 edges, where *k* is some integer. Note that one vertex is a valid tree. 22 23 There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to *n*. For each Ball *i* we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those. 24 25 How many trees are there in the forest? 26 27 Input 28 29 The first line contains single integer *n* (1 ≤ *n* ≤ 104) — the number of Balls living in the forest. 30 31 The second line contains a sequence *p*1, *p*2, ..., *p**n* of length *n*, where (1 ≤ *p**i* ≤ *n*) holds and *p**i* denotes the most distant from Ball *i* relative living on the same tree. If there are several most distant relatives living on the same tree, *p**i* is the id of one with the smallest id. 32 33 It's guaranteed that the sequence *p* corresponds to some valid forest. 34 35 Hacking: To hack someone, you should provide a correct forest as a test. The sequence *p* will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: 36 37 In the first line, output the integer *n* (1 ≤ *n* ≤ 104) — the number of Balls and the integer *m* (0 ≤ *m* < *n*) — the total number of edges in the forest. Then *m* lines should follow. The *i*-th of them should contain two integers *a**i* and *b**i* and represent an edge between vertices in which relatives *a**i* and *b**i* live. For example, the first sample is written as follows: 38 39 ``` 40 5 3 41 1 2 42 3 4 43 4 5 44 ``` 45 46 Output 47 48 You should output the number of trees in the forest where PolandBall lives. 49 50 Interaction 51 52 From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction. 53 54 Examples 55 56 Input 57 58 ``` 59 5 60 2 1 5 3 3 61 ``` 62 63 Output 64 65 ``` 66 2 67 ``` 68 69 Input 70 71 ``` 72 1 73 1 74 ``` 75 76 Output 77 78 ``` 79 1 80 ``` 81 82 Note 83 84 In the first sample testcase, possible forest is: 1-2 3-4-5. 85 86 There are 2 trees overall. 87 88 In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.