topcoder SRM 628 DIV2 BracketExpressions

OpenSoucre發表於2014-07-24

先用dfs搜尋所有的情況,然後判斷每種情況是不是括號匹配

#include <vector>
#include <string>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <climits>
#include <queue>

using namespace std;

class BracketExpressions
{
public:
    string src,dst;
    const string bracket="()[]{}";

    bool check(string& str){
        stack<char> st;
        for(int i = 0 ; i < str.length(); ++ i){
            if(st.empty()) st.push(str[i]);
            else{
                char ch = st.top();
                if((str[i]==']'&& ch=='[')||(str[i] == '}' && ch=='{') || (str[i]==')'&& ch=='(')) st.top();
                else st.push(str[i]);
            }
        }
        cout<<st.size()<<endl;
        return st.empty()?true:false;
    }

    bool dfs(int cur){
        if(cur==src.length()) return check(dst);
        if(src[cur]=='X'){
            bool flag = false;
            for(int i = 0 ; i < bracket.length();++i){
                dst[cur]=bracket[i];
                flag|=dfs(cur+1);
            }
            return flag;
        }else return dfs(cur+1);
    }

    string ifPossible(string expression)
    {
        src=dst=expression;
        return dfs(0)?"possible":"impossible";
    }


};


// Powered by FileEdit
// Powered by TZTester 1.01 [25-Feb-2003]
// Powered by CodeProcessor


// Powered by FileEdit
// Powered by TZTester 1.01 [25-Feb-2003]
// Powered by CodeProcessor

相關文章