// Skwarki [B] n!.cpp : Defines the entry point for the console application.
//
#include <bits/stdc++.h>
using namespace std;
bool checkperm(vector<int> a, int k) {
vector<int> tmp;
int kk = 0;
while (a.size() > 1) {
kk++;
if (kk > k) return false;
if (a[0] > a[1]) {
tmp.push_back(a[0]);
}
for (int i = 1; i < a.size()-1; i++) {
if (a[i] > a[i - 1] && a[i] > a[i + 1]) {
tmp.push_back(a[i]);
}
}
if (a[a.size() - 1] > a[a.size() - 2] && a.size() > 2) {
tmp.push_back(a.back());
}
a.clear();
a = tmp;
tmp.clear();
}
if (kk == k) return true;
return false;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k;
long long p;
cin >> n >> k >> p;
int chck = ceil(log2(double(n)));
if (k > chck) {
cout << 0 << endl;
return 0;
}
vector<int> v(n);
for (int i = 0; i < n; i++) {
v[i] = i + 1;
}
long long res = 0;
do {
if (checkperm(v, k)) res++;
if (res >= p) res %= p;
} while (next_permutation(v.begin(),v.end()));
cout << res << endl;
return 0;
}
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 | // Skwarki [B] n!.cpp : Defines the entry point for the console application. // #include <bits/stdc++.h> using namespace std; bool checkperm(vector<int> a, int k) { vector<int> tmp; int kk = 0; while (a.size() > 1) { kk++; if (kk > k) return false; if (a[0] > a[1]) { tmp.push_back(a[0]); } for (int i = 1; i < a.size()-1; i++) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { tmp.push_back(a[i]); } } if (a[a.size() - 1] > a[a.size() - 2] && a.size() > 2) { tmp.push_back(a.back()); } a.clear(); a = tmp; tmp.clear(); } if (kk == k) return true; return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; long long p; cin >> n >> k >> p; int chck = ceil(log2(double(n))); if (k > chck) { cout << 0 << endl; return 0; } vector<int> v(n); for (int i = 0; i < n; i++) { v[i] = i + 1; } long long res = 0; do { if (checkperm(v, k)) res++; if (res >= p) res %= p; } while (next_permutation(v.begin(),v.end())); cout << res << endl; return 0; } |
English