• C语言数据结构算法之求出栈序列个数、判断出栈序列是否合法、求所有合法出栈序列、入栈次数、出栈次数、


    1. #include<stdio.h>
    2. #include<string.h>
    3. int zz=0;
    4. //出栈序列个数
    5. int Number(char *ch) {
    6. int len=strlen(ch),num=0,fz=1,fm=1;
    7. len=strlen(ch);
    8. for(int i=1,j=2*len; i<=len; i++,j--) {
    9. fm*=i;
    10. fz*=j;
    11. }
    12. return (fz/fm)/(len+1);
    13. }
    14. //判断出栈序列是否合法
    15. void Judge(char *push,char *pop) {
    16. int len=strlen(push);
    17. char sta[256],flag[512]="";
    18. int cur=-1,index=0;
    19. for(int i=0,j=0; i<len; i++) {
    20. sta[++cur]=push[i];
    21. flag[index++]='1';
    22. for(; cur!=-1&&sta[cur]==pop[j]; j++) {
    23. cur--;
    24. flag[index++]='0';
    25. }
    26. }
    27. if(cur==-1) printf("\n合法\t出入栈顺序:%s\n",flag);
    28. else printf("\n不合法\n");
    29. }
    30. //入栈次数
    31. int PushCount(char *seq) {
    32. int count=0;
    33. for(int i=0; i<strlen(seq); i++)
    34. if(seq[i]=='1') count++;
    35. return count;
    36. }
    37. //出栈次数
    38. int PopCount(char *seq) {
    39. int count=0;
    40. for(int i=0; i<strlen(seq); i++)
    41. if(seq[i]=='0') count++;
    42. return count;
    43. }
    44. //求所有合法出栈序列
    45. void AllSeq(int m,int n,char *seq,char *arr) {
    46. char sta[256]="";
    47. int index=0;
    48. if(2*m==n) {
    49. printf("\n%4d\t出入栈顺序:%s\t序列:",++zz,seq);
    50. for(int i=0,j=0; i<n; i++)
    51. if(seq[i]=='1') sta[index++]=arr[j++];
    52. else printf("%c ",sta[--index]);
    53. }
    54. if(PushCount(seq)<m) {
    55. seq[strlen(seq)]='1';
    56. AllSeq(m,n+1,seq,arr);
    57. }
    58. if(PushCount(seq)>PopCount(seq)&&(PushCount(seq)+PopCount(seq))<2*m) {
    59. seq[strlen(seq)]='0';
    60. AllSeq(m,n+1,seq,arr);
    61. }
    62. seq[strlen(seq)-1]=seq[strlen(seq)];
    63. }
    64. int main() {
    65. char push[256],pop[256];
    66. printf("入栈序列:");
    67. scanf("%s",push);
    68. getchar();
    69. printf("待判断出栈序列:");
    70. scanf("%s",pop);
    71. Judge(push,pop);
    72. printf("\n出栈序列个数:%d\n",Number(push));
    73. char seq[512]="";
    74. AllSeq(strlen(push),0,seq,push);
    75. return 0;
    76. }

     

     

  • 相关阅读:
    Python 0/1背包问题
    【力扣周赛】第 112 场双周赛
    springboot中如何进行业务层测试事务回滚
    UniApp文件上传(SpringBoot+Minio)
    【C语言基础】Chap. 5. 语句基础
    4.4 多态性
    python爬虫出现问题
    信息学奥赛一本通:1311:【例2.5】求逆序对
    倒计时5天!飞桨AI Studio星河社区x智海Mo AI大模型创意应用大赛等你来战!
    grafana 密码忘记怎么重置
  • 原文地址:https://blog.csdn.net/weixin_63381305/article/details/127691040