First ask permutation group naked problem.
The second question to consider a loop alone, any exchange of two elements, a little painting will find that the cycle is split into 2, the remaining number of exchanges required to reduce 1, that is, the first step of our arbitrary exchange, can guarantee the least number of exchanges. So the answer to a loop is n (n-1)/2, add up all.
And then we find that in the remaining steps, we just need to swap in the two loops we've pulled out.
#include <cstdio>using namespace std; #define N 50001bool vis[n];int n,op,a[n],sumv,sum2;int Main () {scanf ("%d%d", &N,&OP), for (int i=1;i<=n;++i) scanf ("%d", &a[i]), and for (int i=1;i<=n;++i) if (!vis[i]) { vis[i]=1; int cnt=1; int u=a[i]; while (u!=i) { vis[u]=1; U=a[u]; ++cnt; } sumv+= (cnt-1); sum2+= (cnt* (cnt-1) >>1); } if (op==1) printf ("%d\n", SUMV), Else printf ("%d\n%d\n", sumv,sum2); return 0;}
"Permutation group" CH Round #63-ORZCC Cup # # Save for Exchange