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
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <cstdio>
#include <iostream>

using namespace std;


#define MAX_SIZE 1002

int arr[MAX_SIZE];
int tmp_arr[MAX_SIZE];
bool zu_entfernen[MAX_SIZE]; // to_remove, to_usuniecia
int n, k, p;
int sum = 0;

//Prints the array 
void printArr(int a[], int n)
{
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}

//void checkArray(int arr[], int n) {
void checkArray(int n) {	// Optimizzation (stack size 1 param less)
	for (int i = 0; i < n; i++)
	{
		tmp_arr[i] = arr[i];
		zu_entfernen[i] = false;
	}

	for (int kk = 0; kk < k; kk++)
	{

		for (int i = 0; i < n - 1; i++)
		{
			if (tmp_arr[i] < tmp_arr[i + 1])
			{
				zu_entfernen[i] = true;
			}
			else
			{
				zu_entfernen[i + 1] = true;
			}
		}

		int counter = 0;
		for (int i = 0; i < n; i++)
		{
			if (zu_entfernen[i] == false)
			{
				tmp_arr[counter] = tmp_arr[i];
				counter++;
			}
			else {
				zu_entfernen[i] = false;
			}
		}
		n = counter;

		if (n == 1 && kk != k - 1)
		{
			return;
		}
	}

	if (n == 1)
	{
		sum++;
	}
	//printArr(tmp_arr, n);
}

// Generating permutation using Heap Algorithm 
//void heapPermutation(int arr[], int size, int n)
void heapPermutation(int size, int n)	// Opitimization
{
	// if size becomes 1 then prints the obtained 
	// permutation 
	if (size == 1)
	{
		checkArray(n);

		return;
	}

	for (int i = 0; i < size; i++)
	{
		heapPermutation(size - 1, n);

		// if size is odd, swap first and last 
		// element 
		if (size % 2 == 1)
			swap(arr[0], arr[size - 1]);

		// If size is even, swap ith and last 
		// element 
		else
			swap(arr[i], arr[size - 1]);
	}
}

// Driver code 
int main()
{
	scanf("%d %d %d", &n, &k, &p);

	for (int i = 0; i < n; i++)
	{
		arr[i] = i + 1;
	}

	//int a[] = { 1, 2, 3 };
	//int n = sizeof a / sizeof a[0];
	heapPermutation(n, n);

	printf("%d", sum%p);

	return 0;
}