Test instructions: Give you a permutation, you can exchange two integers at a time (not necessarily adjacent), the minimum number of exchanges to the arrangement into a 1~n ring arrangement. (Both pros and cons are counted)
In fact, is to find the ring, for a chain sequence, the minimum number of exchanges is equal to not in the corresponding position of numbers minus the number of rings.
As far as the proof of this is more detailed: http://www.dewen.io/q/7967#ans16319
So just enumerate the starting point of the ring and it will be OK, Dfs looking for the ring.
#include <bits/stdc++.h>using namespacestd;Const intMAXN = 1e3+233;#defineBug (x) cout<< #x << ' = ' <<x<<endl;intA[MAXN];BOOLVIS[MAXN];intcnt,s;voidDfsintu) { if(Vis[u])return; CNT++; Vis[u]=true; DFS (A[u+s]);}intN;voidDFS2 (intu) { if(vis[n-1-U])return; CNT++; Vis[n-1-U] =true; DFS2 (A[n-1-u+s]);}intMain () {//freopen ("In.txt", "R", stdin); while(~SCANF ("%d", &n) &&N) { for(inti =0; I < n; i++) {scanf ("%d", a+i); A[i+n] =--A[i]; } intAns =Int_max; for(s =0; s < n; s++){ intCur =0; memset (Vis,0,sizeof(VIS)); for(inti =0; I < n; i++)if(!Vis[i]) { if(A[i+s]! =i) {vis[i]=true; CNT =0; DFS (A[i+S]); Cur+=CNT; }ElseVis[i] =true; } ans=min (ans,cur); } Reverse (A,a+2*N); for(s =0; s < n; s++){ intCur =0; memset (Vis,0,sizeof(VIS)); for(inti =0; I < n; i++)if(!Vis[i]) { if(A[i+s]! =i) {vis[i]=true; CNT =0; DFS (A[i+R]); Cur+=CNT; }ElseVis[i] =true; } ans=min (ans,cur); } printf ("%d\n", ans); } return 0;}
UVA 10570 meet with Aliens Alien Party