康托展开

/*

  Name: 康托展开

  Copyright: 始发于goal00001111的专栏;允许自由转载,但必须注明作者和出处

  Author: goal00001111

  Date: 17-11-08 22:50

  Description: 康托展开。

把一个整数X展开成如下形式

 X=a[n]*n!+a[n-1]*(n-1)!+...+a[2]*2!+a[1]*1!

 其中,a为整数,并且0<=a<i,i=1,2,..,n

*/

#include<iostream>

 

using namespace std;

 

long long Cantor(int a[], int n);

 

int main()

{

    const int N = 10;

    int a[N] = {0};

    for (int i=0; i<N; i++)

        a[i] = i + 1;

   

    for (int t=0; t<5; t++)

    {

        for (int i=0; i<N; i++)//随机交换数组元素,得到一个排列

        {

            int pos = rand() % N;

            int temp = a[i];

            a[i] = a[pos];

            a[pos] = temp;

        }

        for (int i=0; i<N; i++)

            cout << a[i] << ' ';

        cout << endl;

       

        cout << Cantor(a, N) << endl << endl;

    }

 

    system("pause");

       return 0;

}

 

long long Cantor(int a[], int n)

{

    long long s = 1;

    long long *p = new long long[n];//用来存储各个全排列的值,p[i]=i!

    for (int i=0; i<n-1; i++)

    {

        s *= i + 1;

        p[i] = s;

    }

    long long sum = 0;

    for (int i=0; i<n-1; i++)

    {

        s = 0;

        for (int j=i+1; j<n; j++)

        {

            if (a[i] > a[j])

                s++;

        }

        sum += s * p[n-2-i];

    }

    delete []p;

    return sum + 1;

}

你可能感兴趣的:(Date,delete,System,存储)