2014년 8월 10일 일요일

FIXPAREN

알고스팟 FIXPAREN

cpp to html



[-] Collapse
#include<iostream>
#include<string>
#include<stack>
#include<cstring>
using namespace std;
int main(){
    char match[126], priority[126];
    memset(match, 0, sizeof(match));
    match['{'] = '}', match['('] = ')', match['<'] = '>', match['['] = ']';
    string str, p;
    stack<pair<char, int> > st;
    int t; cin >> t;
    while (t--){
        cin >> str >> p;
        for (int i = 0; i < p.size(); i++)
            priority[match[p[i]]] = p.size() - i;
        int cIdx = 0;
        for (int i = 0; i < str.size(); i++){
            if (match[str[i]] == 0){
                if (priority[match[st.top().first]] >= priority[str[i]])
                    str[i] = match[st.top().first];
                else
                    str[st.top().second] = str[i] + (str[i] == ')' ? -1 : -2);
                st.pop();
            }
            else st.push(pair<char, int>(str[i], i));
        }
        cout << str << endl;
    }
}

댓글 4개:

  1. 제가 본 코드 중 가장 좋은 코드라고 생각합니다. 도움 많이 됐습니다.

    답글삭제
  2. if (priority[match[st.top().first]] >= priority[str[i]])
    str[i] = match[st.top().first];
    else
    str[st.top().second] = str[i] + (str[i] == ')' ? -1 : -2);
    st.pop();

    이쪽 조건 틀리신것 같습니다 ^^

    답글삭제
  3. 오.. 잘못 된 소스를 올렸었네요. 지적 감사합니다.

    답글삭제