문제 링크입니다: https://www.acmicpc.net/problem/1662
1662번: 압축
압축되지 않은 문자열 S가 주어졌을 때, 이 문자열중 어떤 부분 문자열은 K(Q)와 같이 압축 할 수 있다. K는 한자리 정수이고, Q는 0자리 이상의 문자열이다. 이 Q라는 문자열이 K번 반복된다는 뜻이다. 압축된 문자열이 주어졌을 때, 이 문자열을 다시 압축을 푸는 프로그램을 작성하시오.
www.acmicpc.net
자소서 쓰느라 바빠서 오랜만에 포스팅하네요.
같은 학회원 분이 질문을 하셨던 문제라 풀어봤던 문제였습니다.
이 문제의 핵심은 먼저 괄호의 쌍의 위치를 전처리를 통해 파악하고 재귀함수를 통해 길이를 구하는 것이었습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <stack> | |
using namespace std; | |
const int MAX = 50; | |
string s; | |
int visited[MAX]; | |
int func(int start, int end) | |
{ | |
int result = 0; | |
for (int i = start; i < end; i++) | |
{ | |
if (s[i] == '(') | |
{ | |
int K = s[i - 1] - '0'; | |
result += K * func(i + 1, visited[i]) - 1; | |
i = visited[i]; | |
continue; | |
} | |
result++; | |
} | |
return result; | |
} | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> s; | |
stack<int> st; | |
// 괄호 쌍 인덱스 전처리 | |
for (int i = 0; i < s.length(); i++) | |
{ | |
if (s[i] == '(') | |
{ | |
st.push(i); | |
} | |
else if (s[i] == ')') | |
{ | |
visited[st.top()] = i; | |
st.pop(); | |
} | |
} | |
cout << func(0, s.length()) << "\n"; | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 2842번 집배원 한상덕 (0) | 2019.09.21 |
---|---|
백준 3649번 로봇 프로젝트 (0) | 2019.09.21 |
백준 15655번 N과 M (6) (2) | 2019.08.28 |
백준 15654번 N과 M (5) (0) | 2019.08.25 |
백준 15651번 N과 M (3) (3) | 2019.08.23 |