#include using namespace std; #define FOR(i,a,b) for (int (i)=(a);(i)<(b);(i)++) #define REP(i,n) FOR(i,0,n) #define pb push_back #define ALL(v) (v).begin(), (v).end() typedef vector VI; typedef vector VVI; typedef long double LD; typedef vector VD; typedef vector VVD; const int MAXN = 205; int n, visited[MAXN]; map mapping; void rec(int total, int last, VI v, VVI &partitions) { if (total == n) partitions.pb(v); else { FOR(i, last, n + 1) if (total + i <= n) { v.pb(i); rec(total + i, i, v, partitions); v.pop_back(); } } } // Recursively generate all partitions with sum equal to n. void genAllPartitions() { VVI partitions; VI v; rec(0, 1, v, partitions); sort(ALL(partitions)); mapping.clear(); int idx = 0; for (auto it : partitions) mapping[it] = idx++; } // Gives list of length of permutation cycles in sorted order VI findCycle(VI a) { memset(visited, 0, sizeof(visited)); VI cycles; REP(i, n) if (!visited[i]) { int len = 0, cur = i; while (!visited[cur]) { len++; visited[cur] = true; cur = a[cur]; } cycles.pb(len); } sort(cycles.begin(), cycles.end()); return cycles; } // Generate all the permutations corresponding to each of the partitions VVI genGoodPermutations() { VVI perms; for (auto it : mapping) { VI cycle = it.first; VI v(n); int idx = 0; for (int len : cycle) { if (len == 1) v[idx] = idx; else { int prev = idx; REP(i, len - 1) { v[idx] = idx + 1; idx++; } v[idx] = prev; } idx++; } perms.pb(v); } return perms; } VVD createEquations(int N, VD &B) { VVD A(N, VD(N)); VVI perms = genGoodPermutations(); int idx = 0; for (auto perm : perms) { A[idx][mapping[findCycle(perm)]] += 1.0; if (is_sorted(ALL(perm))) { idx++; continue; } REP(i, n) FOR(j, i + 1, n) { VI newPerm = perm; swap(newPerm[i], newPerm[j]); VI cycle = findCycle(newPerm); A[idx][mapping[cycle]] -= 2.0 / ((LD) n * (n - 1)); } B[idx] += 1; idx++; } return A; } const LD EPS = 1e-9; // Solve A X = b. VD gauss(const VVD &A, const VD &b) { int n = A.size(); VVD B(n, VD(n + 1)); REP(i, n) { REP(j, n) B[i][j] = A[i][j]; B[i][n] = b[i]; } REP(i, n) { int pivot = i; FOR(j, i, n) if (fabs(B[j][i]) > fabs(B[pivot][i])) pivot = j; swap(B[i], B[pivot]); if (fabs(B[i][i]) < EPS) { assert(false); return VD(); } for (int j = n; j >= i; j--) B[i][j] /= B[i][i]; REP(j, n) if (i != j) FOR(k, i + 1, n + 1) B[j][k] -= B[j][i] * B[i][k]; } VD x(n); REP(i, n) x[i] = B[i][n]; return x; } void solve(VI a) { genAllPartitions(); VI cycles = findCycle(a); int idx = mapping[cycles]; int N = mapping.size(); VD b(N); VVD A = createEquations(N, b); VD res = gauss(A, b); printf("%.18Lf\n", res[idx]); } int main() { int T, tc = 1; scanf("%d", &T); while (T--) { cerr << "processed test " << tc++ << endl; scanf("%d", &n); VI a(n); REP(i, n) { scanf("%d", &a[i]); a[i]--; } solve(a); } return 0; }