标签:
//模拟过程如下,dfs来填充入栈和出栈的标志
#include<iostream> #include<cstring> #include<cstdio> #include<stack> #define N 100 using namespace std; int a[N]; int p[2*N]; int pre[2*N]; int used[2*N]; int index[2*N];//如果a[i]==1,那么表示第index[i]个数入栈 int n; int cnt;//记录多少个出栈的序列 int C(int n){ int ans=1; int m = 2*n; int nn = n; for(int i=1; i<=n; ++i){ ans *= m--; ans /= i; } return ans/(nn+1); } void solve(){ memset(pre, 0, sizeof(pre)); memset(used, 0, sizeof(used)); int prek = 0; for(int i=1; i<=2*n; ++i){ if(a[i] == 1){ pre[i] = prek; prek = i; } else { int ii = prek; while(used[ii]) ii = pre[ii]; cout<<p[index[ii]]<<" ";//出栈 used[ii] = 1; pre[prek] = pre[ii]; } } cout<<endl; } void solve1(){ stack<int>s; int k=1; for(int i=1; i<=2*n; ++i){ if(a[i] == 1) s.push(p[k++]); else { cout<<s.top()<<" "; s.pop(); } } cout<<endl; } void dfs(int k, int cnt0, int cnt1){ if(k>2*n){ //solve(); solve1(); ++cnt; return ; } if(cnt1<n){//入栈 a[k] = 1; index[k] = cnt1+1;//第几个数入栈 dfs(k+1, cnt0, cnt1+1); } if(cnt0<cnt1){//出栈 a[k] = 0; dfs(k+1, cnt0+1, cnt1); } } int main(){ cin>>n; for(int i=1; i<=n; ++i) cin>>p[i]; dfs(1, 0, 0); cout<<endl<<"模拟个数:"<<cnt<<endl; cout<<"公式个数:"<<C(n)<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/hujunzheng/p/4845354.html