• FZU Problem 2030 括号问题


    /*
      对于小数据用这dfs,大数据就用递推的思想。
    */
    #include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> #include <math.h> #include <queue> #include <map> #include <stack> #include <vector> using namespace std ; const int maxn = 20; char str[maxn]; int num[maxn]; bool judge(char *st){ int top = 0; int l = strlen(st); for(int i = 0;i < l;i++){ if(st[i] == '(') top++; else if(top) top--; else return 0; } if(top) return 0; return 1; } int len,ans; void dfs(int x){ if(x == len){ if(judge(str)) ans++; } else{ str[num[x]] = '('; dfs(x+1); str[num[x]] = ')'; dfs(x+1); } } int main(){ //freopen("test.txt","r",stdin); //freopen("out.txt","w",stdout); while(~scanf("%s",str)){ len = 0; int l = strlen(str); for(int i = 0;i < l;i++){ if(str[i] == '?') num[len++] = i; } ans = 0; dfs(0); printf("%d\n",ans); } return 0; }
    /*
      对于数据比较小的,直接用dfs即可,数据要是比较大的话,dfs肯定TLE,所以这时应该采取递推的思想。
    */
    #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; const int maxn = 1005; char str[maxn]; int dp[maxn][maxn]; int main(){ while(~scanf("%s",str)){ int len = (int)strlen(str); dp[0][1] = 1; for(int i = 1;i < len;i++){ for(int j = 0;j < len;j++){ if(str[i] == '(') dp[i][j] = dp[i-1][j-1]; else if(str[i] == ')') dp[i][j] = dp[i-1][j+1]; else dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1]; } } /*for(int i = 0;i < len;i++){ for(int j =0;j < len;j++) printf("%d ",dp[i][j]); printf("\n"); }*/ printf("%d\n",dp[len - 1][0]); } return 0; }
  • 相关阅读:
    PTA 1007 Maximum Subsequence Sum (25 分)
    c++ primer 6th 函数
    redis源码笔记(持续更新)
    c文件函数总结
    PAT基础知识点
    vector模糊查询
    c++ primer 15th 面向对象程序设计
    c++ primer 18th 用于大型程序的工具
    c++ primer 19th 特殊工具与技术
    MFC TreeCtrl
  • 原文地址:https://www.cnblogs.com/Roly/p/3077858.html
Copyright © 2020-2023  润新知