- #include<stdio.h>
- #include<string.h>
- int zz=0;
- //出栈序列个数
- int Number(char *ch) {
- int len=strlen(ch),num=0,fz=1,fm=1;
- len=strlen(ch);
- for(int i=1,j=2*len; i<=len; i++,j--) {
- fm*=i;
- fz*=j;
- }
- return (fz/fm)/(len+1);
- }
- //判断出栈序列是否合法
- void Judge(char *push,char *pop) {
- int len=strlen(push);
- char sta[256],flag[512]="";
- int cur=-1,index=0;
- for(int i=0,j=0; i<len; i++) {
- sta[++cur]=push[i];
- flag[index++]='1';
- for(; cur!=-1&&sta[cur]==pop[j]; j++) {
- cur--;
- flag[index++]='0';
- }
- }
- if(cur==-1) printf("\n合法\t出入栈顺序:%s\n",flag);
- else printf("\n不合法\n");
- }
- //入栈次数
- int PushCount(char *seq) {
- int count=0;
- for(int i=0; i<strlen(seq); i++)
- if(seq[i]=='1') count++;
- return count;
- }
- //出栈次数
- int PopCount(char *seq) {
- int count=0;
- for(int i=0; i<strlen(seq); i++)
- if(seq[i]=='0') count++;
- return count;
- }
- //求所有合法出栈序列
- void AllSeq(int m,int n,char *seq,char *arr) {
- char sta[256]="";
- int index=0;
- if(2*m==n) {
- printf("\n%4d\t出入栈顺序:%s\t序列:",++zz,seq);
- for(int i=0,j=0; i<n; i++)
- if(seq[i]=='1') sta[index++]=arr[j++];
- else printf("%c ",sta[--index]);
- }
- if(PushCount(seq)<m) {
- seq[strlen(seq)]='1';
- AllSeq(m,n+1,seq,arr);
- }
- if(PushCount(seq)>PopCount(seq)&&(PushCount(seq)+PopCount(seq))<2*m) {
- seq[strlen(seq)]='0';
- AllSeq(m,n+1,seq,arr);
- }
- seq[strlen(seq)-1]=seq[strlen(seq)];
- }
- int main() {
- char push[256],pop[256];
- printf("入栈序列:");
- scanf("%s",push);
- getchar();
- printf("待判断出栈序列:");
- scanf("%s",pop);
- Judge(push,pop);
- printf("\n出栈序列个数:%d\n",Number(push));
- char seq[512]="";
- AllSeq(strlen(push),0,seq,push);
- return 0;
- }