🔗 문제
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
라이브러리 없이 푼 버전
더보기
🖍 풀이
인접한 숫자는 ‘x’로 변경해주고 ‘x’를 제외한 암호문을 출력해주었다.
- 비밀번호(pwd)를 string으로 받는다.
- 가장 먼저 나오는 숫자의 인덱스 번호를 pre에 저장한다.
- pre+1 부터 자와 같은 쌍인지 확인한다.
- 같은 쌍 O → pwd[pre], pwd[i]를 ‘x’로 변경하고 반복문을 break한다.
- 같은 쌍 X → pre = i로 바꿔준다.
- 만약 i가 N이 되도록 break문을 통과하지 않았다면 더 이상 암호를 압축할 수 없으니 종료시켜준다.
💾 소스
#include <iostream>
#include <string>
int main()
{
int T = 10;
for(int tc=1 ; tc<=T; ++tc)
{
int N = 0;
std::string answer, pwd;
std::cin >> N >> pwd;
answer.reserve(N);
while(1)
{
int i = 0, pre = 0;
for(pre=0; pre<N; ++pre)
if(pwd[pre]!='x')
break;
for(i=pre+1; i<pwd.size(); ++i)
{
if(pwd[i] == 'x') continue;
if(pwd[pre] == pwd[i])
{
pwd[pre] = pwd[i] = 'x';
break;
}
pre = i;
}
if(i==N) break;
}
for(int i=0; i<pwd.size(); ++i)
{
if(pwd[i] != 'x')
{
answer +=pwd[i];
}
}
std::cout << '#' << tc << ' ' << answer <<'\\n';
}
return 0;
}
🖍 풀이
스택을 이용해서 top과 비교하면 쉽게 풀 수 있다.
1, 2, 3, 3, 2, 4 가 input인 예를 들어보자.
[ 1, 2, 3 까지 stack에 값을 넣어줬다.
이 다음으로 3을 넣으려고 하니 stack.top과 같은 쌍이다.
→ top을 빼준다.
💾 소스
#include <iostream>
#include <stack>
int main()
{
int T = 10;
for(int tc=1 ; tc<=T; ++tc)
{
int N, answer = 0;
char pwd[102];
std::stack<int> stk;
std::cin >> N;
for(int i=0; i<N; ++i)
std::cin >> pwd[i];
//solve
stk.push(pwd[0]-'0');
for(int i=1; i<N; ++i)
{
if(!stk.empty() &&
(stk.top() == (pwd[i]-'0')))
stk.pop();
else
stk.push(pwd[i]-'0');
}
// answer
int tmp = 1;
while(!stk.empty())
{
answer += (stk.top() * tmp);
tmp*=10;
stk.pop();
}
std::cout << '#' << tc << ' ' << answer <<'\\n';
}
return 0;
}