๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 2504๋ฒˆ - ๊ด„ํ˜ธ์˜ ๊ฐ’

by ์•ˆ์ฃผํ˜• 2022. 3. 16.

๋ฌธ์ œ

 

2504๋ฒˆ: ๊ด„ํ˜ธ์˜ ๊ฐ’

4๊ฐœ์˜ ๊ธฐํ˜ธ ‘(’, ‘)’, ‘[’, ‘]’๋ฅผ ์ด์šฉํ•ด์„œ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ด„ํ˜ธ์—ด ์ค‘์—์„œ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ด๋ž€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋œ๋‹ค. ํ•œ ์Œ์˜ ๊ด„ํ˜ธ๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ‘()’์™€ ‘[]’๋Š” ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ด๋‹ค.  ๋งŒ์ผ

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <stack>
#include <map>
using namespace std;

int main(){
    string s; cin>>s;
    stack<char>st;
    map<char,int>m;
    int ans = 0, temp = 1;
    
    for(int i=0; i<s.length(); i++) m[s[i]]++;
    if(m['[']!=m[']']||m['(']!=m[')']){
        cout<<0;
        return 0;
    }
    
    
    for(int i=0; i<s.length(); i++){
        if(s[i]=='('){
            temp *= 2;
            st.push('(');
        }
        else if(s[i]=='['){
            temp *= 3;
            st.push('[');
        }
        else if(s[i]==')'){
            if(st.empty()||st.top()=='['){
                ans = 0;
                break;
            }
            else if(s[i-1]=='('){
                ans+=temp;
                temp/=2;
                st.pop();
            }
            else{
                temp/=2;
                st.pop();
            }
        }
        else if(s[i]==']'){
            if(st.empty()||st.top()=='('){
                ans = 0;
                break;
            }
            else if(s[i-1]=='['){
                ans+=temp;
                temp/=3;
                st.pop();
            }
            else{
                temp/=3;
                st.pop();
            }
        }
    }
    cout<<ans;
}

 

ํ’€์ด

์–ด๋ ค์› ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ ์ดํ•ด๋Š” ๊ฐ„๋‹จํ–ˆ์œผ๋‚˜ ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„์„ ํ•ด์•ผ ํ• ์ง€ ๊ณ„์† ๋จธ๋ฆฟ์†์—์„œ ๋งด๋Œ์•˜์Šต๋‹ˆ๋‹ค. 

์ œ ํ’€์ด ๋ฐฉ์‹์œผ๋กœ ์„ค๋ช…์„ ๋“œ๋ฆฌ๋ฉด ์ž…๋ ฅ ๊ฐ’์ด "(()[[]])([])" ์ผ๋–„ 2x2 + 3x3x2 + 3x2์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๊ณ„์‚ฐํ•˜๊ฒŒ๋” ์„ค๊ณ„ํ–ˆ์Šต๋‹ˆ๋‹ค. 

๋Œ“๊ธ€