您的位置:首页 > 其它

FZU Problem 2030 括号问题

2014-03-14 17:21 253 查看
/*
  对于小数据用这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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: