题目
TLE代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int cntall = 1, m1, m2;
string s = "abcdefghijklnopqr";
while (next_permutation(s.begin(), s.end()))
{
if (s == "aejcldbhpiogfqnkr")
m1 = cntall;
else if (s == "ncfjboqiealhkrpgd")
m2 = cntall;
cntall++;
}
cout << min(abs(m2 - m1), cntall - abs(m2 - m1));
}
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL a1, a2;
LL f[20];
void get_f(int n)
{
f[1] = 1;
for (int i = 2; i <= n; i++)
{
f[i] = i * f[i - 1];
}
}
void canto(string str, LL &x)
{
int n = str.size();
for (int i = 0; i < n; i++)
{
int temp = 0;
for (int j = i + 1; j < n; j++)
{
if (str[i] > str[j])
temp++;
}
x += temp * f[n - 1 - i];
}
}
int main()
{
get_f(17);
string s1 = "aejcldbhpiogfqnkr";
string s2 = "ncfjboqiealhkrpgd";
canto(s1, a1), canto(s2, a2);
cout << min(abs(a1 - a2), f[17] - abs(a1 - a2));
}
补充:反康托展开
string r_canto(string str, LL x)
{
string retv = "";
int n = str.size();
bool st[n] = {false};
for (int i = n - 1; i >= 1; i--)
{
int k = x / f[i];
x = x % f[i];
for (int j = 0; j < n; j++)
{
if (!st[j])
k--;
if (k < 0)
{
st[j] = true;
retv += str[j];
break;
}
}
}
for (int i = 0; i < n; i++)
{
if (!st[i])
{
retv += str[i];
break;
}
}
return retv;
}