Link to the question: Ultraviolet A 11330-Andy's shoes
Andy has a lot of shoes and is lost everywhere. Later, he put all his shoes back in a row, ensuring that the left and right sides of the shoes alternate, but the colors are mixed. How many times can he move his shoes at least.
Solution: it corresponds to the left shoes with an odd number and the right shoes with an even number. A pair of shoes only has one left shoes and one right shoes, so that they do not change to the left shoes, change the right shoe based on the position of the left shoe. The position of the right shoe is a replacement. The replacement cycle is divided into X unrelated cycles, ANS = N-x
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1e4+5;int n, pos[maxn], v[maxn], arr[maxn];int solve () { int ret = 0; memset(v, 0, sizeof(v)); for (int i = 0; i < n; i++) { if (v[i]) continue; ret++; int mv = i; while (v[mv] == 0) { v[mv] = 1; mv = arr[mv]; } } return ret;}int main () { int cas, x; scanf("%d", &cas); while (cas--) { scanf("%d", &n); for (int i = 0; i < 2 * n; i++) { if (i&1) scanf("%d", &arr[i/2]); else { scanf("%d", &x); pos[x] = i/2; } } for (int i = 0; i < n; i++) arr[i] = pos[arr[i]]; printf("%d\n", n - solve()); } return 0;}