Cantor expansion and inverse expansion

Expand Cantor
Cantor expand the current arrangement is represented by full permutation of n different elements of the ranking. For example, 213 ranks third among all the 3 numbers.

Cantor expansion: ans = an*(n-1)! + an-1*(n-2)!+...+a2*1!+a1*0!

ll Work(char str[])
{
	ll ans = 0;
	int len = strlen(str);
	for(int i=0; i<len; i++)
	{
		ll temp = 0;
		for(int j=i+1; j<len; j++)
		{
			if(s[j]<s[i])
			{
				temp++;
			}
		}
		ans += temp*f[len-i+1];    //f[]为阶乘
	}
	return ans+1;
}

Cantor inverse expansion

Cantor inverse expansion, find the n-th largest permutation in the total permutations of m numbers

void Work(ll n, ll m)
{
	n--;
	vector<int> v;
	vector<int> a;
	for(int i=1; i<=m; i++)
		v.push_back(i);
	for(int i=1; i<=m; i++)
	{
		ll r = n%f[m-i];
		ll t = n/f[m-i];
		n = r;
		sort(v.begin(), v.end());
		a.push_back(v[t]);
		v.erase(v.begin()+t);
	}
	vector<int>::iterator it = a.begin();
	for(; it!=a.end(); it++)
		cout<<*it;
	cout<<endl;
}


Guess you like

Origin blog.csdn.net/qq_31281327/article/details/76340357