http://community.topcoder.com/stat?c=problem_statement&pm=13243

就是能否通过把字符串中的'X'替换成"()", "[]", and "{}"来变成合法的括号字符串,

"([]X()[()]XX}[])X{{}}]"
Returns: "possible"
You can replace 'X's respectively with '{', '(', ')' and '['.

DFS搜索,Valid的判断使用stack。

#include <stack>
#include <vector>
#include <string>
using namespace std; class BracketExpressions {
public:
string candidates; string ifPossible(string expression)
{
candidates = "()[]{}";
vector<int> xPos;
for (int i = 0; i < expression.length(); i++)
{
if (expression[i] == 'X')
{
xPos.push_back(i);
}
}
bool possible = ifPossRe(expression, 0, xPos);
if (possible)
return "possible";
else
return "impossible";
} bool isValid(const string &expression)
{
stack<char> stk;
for (int i = 0; i < expression.length(); i++)
{
if (stk.empty())
{
stk.push(expression[i]);
}
else if (match(stk.top(), expression[i]))
{
stk.pop();
}
else
{
stk.push(expression[i]);
}
}
return stk.empty();
} bool match(char a, char b)
{
if (a == '(' && b == ')') return true;
if (b == '(' && a == ')') return true;
if (a == '[' && b == ']') return true;
if (b == '[' && a == ']') return true;
if (a == '{' && b == '}') return true;
if (b == '{' && a == '}') return true;
return false;
} bool ifPossRe(string &expression, int idx, vector<int> &xPos)
{
if (idx == xPos.size())
{
return isValid(expression);
}
int n = xPos[idx];
for (int i = 0; i < candidates.length(); i++)
{
char ch = expression[n];
expression[n] = candidates[i];
bool res = ifPossRe(expression, idx+1, xPos);
expression[n] = ch;
if (res)
return true;
}
return false;
}
};

http://apps.topcoder.com/wiki/display/tc/SRM+628

但其实判断Backet合法的代码是错的,因为没有判断先有左括号再有右括号,以下做法更好更简洁。

bool correctBracket(string exp)
{
stack<char> s;
// an assoicaitive array: opos[ ')' ] returns '(', opos[ ']' ] is '[', ...
map<char,char> opos = {
{ ')', '(' },
{ ']', '[' },
{ '}', '{' },
};
for (char ch: exp) {
// we push opening brackets to the stack
if (ch == '(' || ch == '[' || ch == '{' ) {
s.push(ch);
} else {
// If we find a closing bracket, we make sure it matches the
// opening bracket in the top of the stack
if (s.size() == 0 || s.top() != opos[ch]) {
return false;
} else {
// then we remove it
s.pop();
}
}
}
// stack must be empty.
return s.empty();
}

解法中还是用了基于6的幂来计算所有组合,比DFS要快。

string ifPossible(string expression)
{
vector<int> x;
int n = expression.size();
for (int i = 0; i < n; i++) {
if (expression[i] == 'X') {
x.push_back(i);
}
}
int t = x.size(); // to easily convert to base 6 we precalculate the powers of 6:
int p6[6];
p6[0] = 1;
for (int i = 1; i < 6; i++) {
p6[i] = 6 * p6[i - 1];
} const char* CHARS = "([{)]}";
for (int m = 0; m < p6[t]; m++) {
string nexp = expression;
for (int i = 0; i < t; i++) {
// (m / p6[i]) % 6 extracts the i-th digit of m in base 6.
nexp[ x[i] ] = CHARS[ (m / p6[i]) % 6 ];
}
if (correctBracket(nexp)) {
return "possible";
}
} return "impossible";
}

  

*[topcoder]BracketExpressions的更多相关文章

  1. topcoder SRM 628 DIV2 BracketExpressions

    先用dfs搜索所有的情况,然后判断每种情况是不是括号匹配 #include <vector> #include <string> #include <list> # ...

  2. TopCoder kawigiEdit插件配置

    kawigiEdit插件可以提高 TopCoder编译,提交效率,可以管理保存每次SRM的代码. kawigiEdit下载地址:http://code.google.com/p/kawigiedit/ ...

  3. 记第一次TopCoder, 练习SRM 583 div2 250

    今天第一次做topcoder,没有比赛,所以找的最新一期的SRM练习,做了第一道题. 题目大意是说 给一个数字字符串,任意交换两位,使数字变为最小,不能有前导0. 看到题目以后,先想到的找规律,发现要 ...

  4. TopCoder比赛总结表

    TopCoder                        250                              500                                 ...

  5. Topcoder几例C++字符串应用

    本文写于9月初,是利用Topcoder准备应聘时的机试环节临时补习的C++的一部分内容.签约之后,没有再进行练习,此文暂告一段落. 换句话说,就是本文太监了,一直做草稿看着别扭,删掉又觉得可惜,索性发 ...

  6. TopCoder

    在TopCoder下载好luncher,网址:https://www.topcoder.com/community/competitive%20programming/ 选择launch web ar ...

  7. TopCoder SRM 596 DIV 1 250

    body { font-family: Monospaced; font-size: 12pt } pre { font-family: Monospaced; font-size: 12pt } P ...

  8. 求拓扑排序的数量,例题 topcoder srm 654 div2 500

    周赛时遇到的一道比较有意思的题目: Problem Statement      There are N rooms in Maki's new house. The rooms are number ...

  9. TopCoder SRM 590

     第一次做TC,不太习惯,各种调试,只做了一题...... Problem Statement     Fox Ciel is going to play Gomoku with her friend ...

随机推荐

  1. 演出排期JavaScript

    <script language="JavaScript" type="text/javascript"> var diarydays=" ...

  2. 通过百度地图API定位--第三方开源--百度地图(一)

    1.把百度地图定位API(下载地址:http://lbsyun.baidu.com/sdk/download?selected=location)里面的libs复制到自己的项目libs里面 2.进行相 ...

  3. require.js入门指南(一)

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  4. 绘制dot 图

    常用参数 格式:dot -T<type> -o<outfile> <infile.dot> 输入文件是<infile.dot>,生成的格式由<ty ...

  5. Java从入门到精通——数据库篇Oracle 11g服务详解

    装上Oracle之后大家都会感觉到我们的电脑慢了下来,如何提高计算机的速度呢?我们应该打开必要的服务,关闭没有用的服务.下面是Oracle服务的详解: Oracle ORCL VSS Writer S ...

  6. HighCharts学习笔记

    目录 xAxis自定义时间刻度的显示 xAxis自定义时间刻度 我们先来看下HighCharts图表的xAxis对象有哪些属性(红色标记重要属性): allowDecimals: Booleancat ...

  7. 信息传递--NOIP2015 day1 T2--暴力

    这道题我用了判联通量加暴力,但联通量判炸了....然后从code[VS]上看到个不错的代码,就拿来了^_^... 基本思路是去掉环外的点,然后走每一个联通块. #include <iostrea ...

  8. startDiscovery() and startLeScan().

    You have to start a scan for Classic Bluetooth devices with startDiscovery() and a scan for Bluetoot ...

  9. SQL Server 2008导出数据为SQL脚本的操作步骤

    以前我们要将一个表中的数据导出为脚本,那么只有在网上找一个导出数据的Script,然后运行就可以导出数据脚本了.现在在SQL Server 2008的Management Studio中增加了一个新特 ...

  10. JSTL标签总结

    一.JSTL简介: 1.JSP标准标签库JSTL(JSP Standard Tag Library)是一个JSP标签集合,它封装了JSP应用的通用核心功能. 2.JSTL支持通用的.结构化的任务.比如 ...