提交时间:2024-08-30 15:13:57

运行 ID: 32049

#include<bits/stdc++.h> #define int long long using namespace std; stack<int>a,b,s1,s2; struct node{ int a,b,s1,s2; }; bool operator<(node x,node y){ if(x.a!=y.a)return x.a<y.a; else if(x.b!=y.b)return x.b<y.b; else if(x.s1!=y.s1)return x.s1<y.s1; else return x.s2<y.s2; } int ha(stack<int> s){ int res=0; while(s.size()){ res=res*13+s.top(); s.pop(); } return res; } int T,n,p; void read(int &x){ x=0; bool f=0; char c=getchar(); while(!isdigit(c)){ if(c=='-')f=1; c=getchar(); } while(isdigit(c)){ x=x*10+c-'0'; c=getchar(); } if(f)x=-x; return; } set<stack<int>>s; map<node,bool>vis; void dfs(){ int a1=ha(a),b1=ha(b),s11=ha(s1),s21=ha(s2); if(vis[{a1,b1,s11,s21}])return; else vis[{a1,b1,s11,s21}]=1; if(a.size()==n){ s.insert(a); return; } if(b.size()){ s2.push(b.top()); b.pop(); dfs(); b.push(s2.top()); s2.pop(); } if(s2.size()&&(!s1.size()||s2.top()<s1.top())){ s1.push(s2.top()); s2.pop(); dfs(); s2.push(s1.top()); s1.pop(); } if(s1.size()){ a.push(s1.top()); s1.pop(); dfs(); s1.push(a.top()); a.pop(); } return; } void slv(){ read(n),read(p); while(b.size())b.pop(); for(int i=n;i>=1;i--)b.push(i); s.clear(); vis.clear(); dfs(); int res=1; for(int i=n;i>=1;i--)res*=i; cout<<res-s.size()<<endl; } signed main(){ // freopen("sort.in","r",stdin); // freopen("sort.out","w",stdout); read(T); while(T--)slv(); return 0; }