1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <vector>
using namespace std;
using INT = unsigned long long;
//==========================================================
INT Factorial( int N ){ return N <= 1 ? N : N * Factorial( N - 1 ); }
//==========================================================
INT order( const vector<int> &A )
{
INT result = 0;
int N = A.size();
INT nFactorial = Factorial( N );
for ( int p = 0; p < N - 1; p++ )
{
nFactorial /= ( N - p ); // how many permutations of REMAINING elements after p
int position = 0; // rank in A[p], ... , A[N-1]
for ( int j = p + 1; j < N; j++ ) if ( A[p] > A[j] ) position++;
result += position * nFactorial;
}
return result;
}
//==========================================================
int main()
{
bool oneBased = false; // change to true if you want to count from 1
// Order assumed as following tests
vector< vector<int> > tests = { {0,1,2,3}, {0,1,3,2}, {0,2,1,3}, {0,2,3,1}, {0,3,1,2}, {0,3,2,1},
{1,0,2,3}, {1,0,3,2}, {1,2,0,3}, {1,2,3,0}, {1,3,0,2}, {1,3,2,0},
{2,0,1,3}, {2,0,3,1}, {2,1,0,3}, {2,1,3,0}, {2,3,0,1}, {2,3,1,0},
{3,0,1,2}, {3,0,2,1}, {3,1,0,2}, {3,1,2,0}, {3,2,0,1}, {3,2,1,0} };
for ( vector<int> &A : tests ) cout << order( A ) + oneBased << '\n';
}
|