백준 algorithm

백준 10799 - 쇠막대기

cosmohoo 2020. 3. 3. 00:24
반응형

문제 설명 

 

 

 

stack을 사용하여 풀 수 있다. 

-> ' ( '를 만나면 stack에 해당 index를 push한다. 

-> ' ) '를 만나면 stack의 top과 ' ) '를 가리키는 인덱스의 크기가 1이면 레이저이므로 stack의 사이즈를 answer에 더한다. 

-> 위의 값이 1이 아닌 경우 answer에 1을 더한다. 

 

 

 


#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    
    string str;
    cin>>str;
    
    stack<int> st;
    int answer=0;
    
    int size=str.length()-1;
    int index=0;
    while(index<=size)
    {
        if(str[index]=='(')st.push(index++);// '(' case
        else// ')' case
        {
            if( ( index-st.top() )==1)//laser
            {
                st.pop();
                answer+=st.size();
                index++;
            }
            else//fe Bar
            {
                st.pop();
                answer+=1;
                index++;
            }
        }
    }
    cout << answer<<'\n';
    return 0;
}

반응형