PS/그리디 알고리즘[Greedy]

백준 4889 안정적인 문자열(c++)

SeungbeomKim 2022. 7. 17. 16:40
반응형

https://www.acmicpc.net/problem/4889

 

4889번: 안정적인 문자열

입력은 여러 개의 데이터 세트로 이루어져 있다. 각 데이터 세트는 한 줄로 이루어져 있다. 줄에는 여는 괄호와 닫는 괄호만으로 이루어진 문자열이 주어진다. 문자열의 길이가 2000을 넘는 경우

www.acmicpc.net

<코드>

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

int main()
{
	string s;
	stack<char>st;
	int start=1;
	while(cin>>s)
	{
		int cnt=0;
		if(s[0]=='-') break;
			for(int i=0;i<s.size();i++)
			{
				if(s[i]=='{') st.push(s[i]);
				else if(s[i]=='}')
				{
					if(!st.empty() && st.top()=='{') st.pop();
					else st.push(s[i]);
				}
			}
			while(!st.empty())
			{
				char c1 = st.top();
				st.pop();
				char c2 = st.top();
				st.pop();
				if(c1!=c2) cnt+=2;
				else cnt+=1;
				
			}
			cout<<start<<"."<<' '<<cnt<<'\n';
			start++;
		}
		
		
}

스택을 이용한 괄호 검사 알고리즘으로 문제를 해결하였다.

{}인 경우에는 pop해주고 그렇지 않은 경우에 대해서 대비해야된다.

}{ 이 경우에는 원소 교환을 2번 해주어야 한다.

}}, {{ 이 경우에는 원소 교환을 1번 해주어야 한다.

반응형

'PS > 그리디 알고리즘[Greedy]' 카테고리의 다른 글

백준 19598 최소 회의실(c++)  (0) 2022.07.20
백준 13975 파일 합치기 3(c++)  (0) 2022.07.19
백준 1758 알바생(c++)  (0) 2022.07.17
백준 13164 행복 유치원(c++)  (1) 2022.07.11
백준 19941 햄버거 분배  (0) 2022.07.03