Files
python/TangDou/AcWing/KangTuo/Cantor.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

34 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
// 阶乘表
int fact[20];
void init_fact(int n) {
fact[0] = 1; // 0的阶乘为1
for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
}
// 康托展开
int cantor(string str) {
int x = 1; // 注意,因为 12345 是算作0开始计算的,最后结果要把12345看作是第一个
int len = str.size();
for (int i = 0; i < len; i++) {
int smaller = 0; // 在当前位之后小于其的个数
for (int j = i + 1; j < len; j++)
if (str[i] > str[j]) smaller++;
// 两种方法:
// ① 往后看,计算str[i]是第几大的数,或者说计算有几个比他小的数
// ② 往前看,计算出现了几个比自己小的数,从自己身上扣除掉逆序数量,也就是后面剩余比自己小的数量
x += smaller * fact[len - i - 1]; // 乘上阶乘
}
return x;
}
int main() {
// 初始化10以内的阶乘表
init_fact(10);
string str = "52413";
// 康托展开
cout << cantor(str) << endl;
return 0;
}