Test instructions: Given an arrangement, you can exchange two numbers at a time and turn it into a 1~n ring arrangement with the fewest number of times.
Analysis: Violence problem. It is easy to think of all the cases and then the least number of them, that is to say, we have all the possible formation of the annular arrangement of all, and then select the least.
Then open a twice-fold array, then two times from 1 to N, then choose n each time, do violence, each find a different, go to this position should be put, and then exchange. Note two positive and reverse order violence.
#include <iostream> #include <cmath> #include <cstdlib> #include <set> #include <cstdio># Include <cstring>using namespace std;typedef long long ll;const int INF = 0x3f3f3f3f;const int MAXN = + 5;int a[ MAXN], b[maxn<<1], C[MAXN], D[maxn<<1];int main () {int n; while (scanf ("%d", &n) = = 1 && n) {int ans = INF; for (int i = 0; i < n; ++i) {scanf ("%d", a+i); b[i] = i+1;} memcpy (b+n, B, sizeof (int) *n); memcpy (c, a, sizeof (a)); for (int k = 0; k < n; ++k) {int cnt = 0; memcpy (A, C, sizeof (a)); for (int i = 0, j = k; i < n && cnt < ans; ++j, ++i) {if (a[i] = = B[j]) continue; for (int l = i+1; l < n; ++l) if (b[j] = = A[l]) {a[l] = A[i]; A[i] = B[j]; Break } ++cnt; } ans = min (ans, CNT); } for (int i = 0; I < n; ++i) D[i] = n-i; memcpy (d+n, D, sizeof (int) *n); for (int k = 0; k < n; ++k) {int cnt = 0; memcpy (A, C, sizeof (a)); for (int i = 0, j = k; i < n && cnt < ans; ++j, ++i) {if (a[i] = = D[j]) continue; for (int l = i+1; l < n; ++l) if (d[j] = = A[l]) {a[l] = A[i]; A[i] = D[j]; Break } ++cnt; } ans = min (ans, CNT); } printf ("%d\n", ans); } return 0;}
The code is as follows:
UVa 10570 Meeting with Aliens (violence)