※ 10799 쇠막대기
https://www.acmicpc.net/problem/10799
10799번: 쇠막대기
여러 개의 쇠막대기를 레이저로 절단하려고 한다. 효율적인 작업을 위해서 쇠막대기를 아래에서 위로 겹쳐 놓고, 레이저를 위에서 수직으로 발사하여 쇠막대기들을 자른다. 쇠막대기와 레이저
www.acmicpc.net
#include <iostream>
#include <stack>
using namespace std;
int solution(const string& str) {
stack<char> st;
int answer = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == '(') { //여는 괄호이면 stack에 push
st.push('(');
}
else { //닫는 괄호이면
st.pop();
if (str[i - 1] == '(') { //이전 문자가 (이면 레이저
answer += st.size(); //레이저이면 스택 사이즈만큼 더하기
}
else { //이전 문자가 (가 아니면 쇠막대기의 끝
answer += 1; //쇠막대기의 끝이면 +1
}
}
}
return answer;
}
int main() {
string str;
cin >> str;
int answer = solution(str);
cout << answer;
return 0;
}
'C++' 카테고리의 다른 글
[Algorithm] BFS 백준 7576 토마토 | C++ (0) | 2022.09.08 |
---|---|
[Algorithm] DFS 프로그래머스 92342 양궁대회 | C++ (0) | 2022.09.01 |
[Algorithm] 정렬 백준 10825번 국영수 | C++ (0) | 2022.08.23 |
[Algorithm] 그리디 프로그래머스 42862번 체육복 | C++ (0) | 2022.08.22 |
[Algorithm] 백트래킹 백준 15649번 N과 M (1) | C++ (0) | 2022.08.01 |
댓글