PROBLEM
APPROACH 1
APPROACH 2
In the first approach, I wrote a brute force solution with complexity of O(mn^2), which is enough for the problem. For every i, if the i-th element is equal to i, I ignore it. Or else I search the whole vector for i and when it is found, I check if there is an unordered pair (i, j). If there exists such a pair, the cost is 0. Or else I increment it by 1.
In the second approach, I assumed (x, y) to be the nodes of a graph that are connected. After testing with a few cases, I came to a conclusion that the answer is simply the number of connected components minus 1.
I understand that the second approach may be wrong but I found no flaw in the first one. Please tell me what went wrong.