love[1 … N] // 1‑based indexing where love[i] = j means person i loves person j .
long long ans = 0; // up to N/2 fits in int, but long long is safe for (int i = 1; i <= N; ++i) int j = love[i]; if (i < j && love[j] == i) ++ans; // count each 2‑cycle once cout << ans << '\n'; return 0;
import sys
A is an unordered pair i , j ( i ≠ j ) such that
If i, j is not mutual, at least one of the equalities love[i]=j or love[j]=i is false. Consider the iteration where i is the smaller index of the two. If love[i] ≠ j → the algorithm’s first condition ( j = love[i] ) fails. If love[i] = j but love[j] ≠ i → the second condition fails. Thus the counter is never increased for this unordered pair. ∎ Theorem After processing a test case, mutualPairs equals the total number of mutual‑love pairs in the group. 412. Sislovesme
2 4 2 1 4 3 5 2 3 1 5 4
Memory – The array love[1…N] is stored: . love[1 … N] // 1‑based indexing where love[i]
def solve() -> None: data = sys.stdin.buffer.read().split() it = iter(data) t = int(next(it)) out_lines = [] for _ in range(t): n = int(next(it)) love = [0] + [int(next(it)) for _ in range(n)] # 1‑based list ans = 0 for i in range(1, n + 1): j = love[i] if i < j and love[j] == i: ans += 1 out_lines.append(str(ans)) sys.stdout.write("\n".join(out_lines))
When the loop later reaches i = b , the first condition fails ( b < a is false), so the pair is counted again. ∎ Lemma 3 If a pair i, j is not a mutual‑love pair, the algorithm never increments mutualPairs for it. If love[i] ≠ j → the algorithm’s first
Multiple test cases are given. T // number of test cases (1 ≤ T ≤ 20) N // number of people (1 ≤ N ≤ 10^5) love[1] love[2] … love[N] // N integers, 1 ≤ love[i] ≤ N The sum of N over all test cases does not exceed 10^6 . Output For each test case output a single line containing the number of mutual‑love pairs. Sample Input
love[i] = j and love[j] = i . Your task is to count how many mutual‑love pairs exist in the given group.