#include<bits/stdc++.h>
using namespace std;
int getLeft(vector<int>& t, int p){
do{
p--;
}while(p >= 0 && t[p] == -1);
return (p >= 0 ? t[p] : -1);
}
int getRight(vector<int>& t, int p){
do{
p++;
}while(p < t.size() && t[p] == -1);
return (p < t.size() ? t[p] : -1);
}
int calc(vector<int> t){
int i=0;
int n = t.size();
vector<int> p = t;
while(n > 1){
for(int i=0;i<t.size();i++)
if(t[i] != -1 && max(getLeft(t,i), getRight(t,i)) > t[i]){
p[i] = -1;
n--;
}
t = p;
i++;
}
return i;
}
int main(void){
int n,k,p;
cin >> n >> k >> p;
vector<int> t(n);
iota(t.begin(), t.end(), 1);
vector<int> res(n+1,0);
do{
int o = calc(t);
res[o]++;
}while(next_permutation(t.begin(), t.end()));
cout << res[k]%p << "\n";;
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 55 | #include<bits/stdc++.h> using namespace std; int getLeft(vector<int>& t, int p){ do{ p--; }while(p >= 0 && t[p] == -1); return (p >= 0 ? t[p] : -1); } int getRight(vector<int>& t, int p){ do{ p++; }while(p < t.size() && t[p] == -1); return (p < t.size() ? t[p] : -1); } int calc(vector<int> t){ int i=0; int n = t.size(); vector<int> p = t; while(n > 1){ for(int i=0;i<t.size();i++) if(t[i] != -1 && max(getLeft(t,i), getRight(t,i)) > t[i]){ p[i] = -1; n--; } t = p; i++; } return i; } int main(void){ int n,k,p; cin >> n >> k >> p; vector<int> t(n); iota(t.begin(), t.end(), 1); vector<int> res(n+1,0); do{ int o = calc(t); res[o]++; }while(next_permutation(t.begin(), t.end())); cout << res[k]%p << "\n";; return 0; } |
English