#include<bits/stdc++.h> usingnamespace std; constint FACT[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}; intCantor(int a[], int n) { int x = 0; for (int i = 0; i < n; i++) { int count = 0; for (int j = i + 1; j < n; j++) { if (a[i] > a[j]) count++; } x += FACT[n - i - 1] * count; } return x; } int *InverseCantor(int x, int n) { int *a = newint[n]; vector<int> v; // 存放当前可选数 for (int i = 1; i <= n; i++) v.push_back(i); for (int i = n - 1; i >= 0; i--) { int r = x % FACT[i]; int t = x / FACT[i]; x = r; a[n - i - 1] = v[t]; v.erase(v.begin() + t); // 移除选做当前位的数 } return a; }
intmain() { int a[] = {3, 4, 1, 5, 2}; cout << Cantor(a, 5) << endl; int *b = InverseCantor(7, 4); for (int i = 0; i < 4; i++) cout << b[i] << " "; }