Problem 2030 括号问题
Accept: 597 Submit: 1166
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
给出一个字符串,其中包括3种字符: ‘(‘, ‘)’, ‘?’.其中?表示这个字符可以是’(‘也可以是’)’. 现在给出字符串S,你可以在’?’处填写’(‘ 或者 ‘)’,当然随意填写得到的序列可能是括号不匹配的。例如”(?”,如果你填写’(‘那么”((“是括号不匹配的! 现在你的任务是确定你有多少种填写方案,使得最终的字符串是括号匹配的!2种方案是不同的,当2种方案中至少存在1个填写字符是不同的。 例如,对于”((??))”,我们可以得到2种方案: “((()))”, “(()())”。
Input
数据包含多组测试数据 第一行输入一个字符串S(S的长度不超过16)。
Output
输出一个整数,表示合法的填写方案数。
Sample Input
((??))
Sample Output
2
Source
福州大学第八届程序设计竞赛
最多2^16个搜索。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int maxn =555;
const int inf = 0x3f3f3f3f;
string s;
int ans;
void dfs(int now,int left,int right)
{
if(right>left) return;
if(left-right>(s.length()-now)) return;
if(now==s.length()){
ans++;
return;
}
if(s[now]=='('){
dfs(now+1,left+1,right);
}else if(s[now]==')'){
dfs(now+1,left,right+1);
}else{
dfs(now+1,left+1,right);
dfs(now+1,left,right+1);
}
}
int main()
{
while(cin>>s){
ans=0;
int f=0;
for(int i=0;i<s.length();i++){
if(s[i]=='?') f=1;
}
if(!f){
printf("0\n");
continue;
}
dfs(0,0,0);
printf("%d\n",ans);
}
}