쇠막대기 문제는 생각이 조금 필요한 문제이지만 구현 자체는 굉장히 쉬웠다.

 

레이저일때는 스택에 쌓여있는 막대기의 갯수만큼 총갯수에 더해주면 되고,

 

마지막에 자투리가 떨어져 나갈때 마다 총갯수에 한개를 더해주면 된다.

 

아주정은 티스토리 귀환띠~

 

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


using namespace std;


int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	stack<char> S;
	string input;
	int total = 0;
	cin >> input;
	for (int i = 0; i < input.length(); i++) {
		if (input[i] == '(') {
			S.push(input[i]);
		}
		else if(input[i]==')' and input[i-1]=='('){ // 레이저일때
			S.pop();
			total += S.size();
		}
		else { // 마지막 자투리일때
			total++;
			S.pop();
		}
	}
	cout << total << endl;
}

+ Recent posts