https://www.acmicpc.net/problem/1874
문제 조건을 따르려고 노력했었다. 다만 바킹독이 제공한 정답코드를 보니 설계를 더 잘해야겠다는 생각을 했다.
1. 내 코드
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <deque>
#include <climits>
#include <set>
#include <stack>
using namespace std;
using ll = long long;
int main() {
int n, save = 0;
cin >> n;
stack<int> stk;
vector<char> ans;
int temp;
for (int i = 0; i < n; i++) {
cin >> temp;
// temp가 n과 같을 때를 고려해야 한다
if (temp > save) { //temp = save인 경우는 없다.
for (int j = save + 1; j <= temp; j++) {
stk.push(j);
ans.push_back('+');
}
save = temp;
stk.pop();
ans.push_back('-');
}
else if (!stk.empty() && temp == stk.top()) { //입력값이 stack top과 같을 때
stk.pop();
ans.push_back('-');
}
else if (!stk.empty() && temp < stk.top()) { //입력값이 stack top보다 작을 때
while (!stk.empty() && stk.top() >= temp) {
stk.pop();
ans.push_back('-');
}
}
else {
cout << "NO" << '\n';
return 0;
}
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << '\n';
}
return 0;
}
2. 바킹독 코드
// Authored by : haneulkimdev
// Co-authored by : BaaaaaaaaaaarkingDog
// http://boj.kr/7a18dc82bd4041aaa59c745f06d4ba60
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
stack<int> S;
int cnt = 1;
string ans;
while (n--) {
int t;
cin >> t;
while (cnt <= t) {
S.push(cnt++);
ans += "+\n";
}
if (S.top() != t) {
cout << "NO\n";
return 0;
}
S.pop();
ans += "-\n";
}
cout << ans;
}
/*
현재 처리를 필요로 하는 수는 cnt이다. cnt 이상인 값 t가 주어지면 그 값을 pop할 수 있게 cnt가 t가
될 때 까지 push를 해야 한다(18-21줄). 만약 22번째 줄과 같이 S.top()과 t가 일치하지 않는다면
올바르지 않은 수열이다.
*/
'PS > BOJ' 카테고리의 다른 글
[백준] 3015. 오아시스 재결합(c++) (0) | 2025.02.02 |
---|---|
[백준] 6198. 옥상정원 꾸미기(c++) (0) | 2025.01.31 |
[백준] 10773. 제로(c++) (0) | 2025.01.26 |
[백준] 10828. 스택(c++) (0) | 2025.01.26 |
[백준] 1158. 요세푸스 문제(c++) (0) | 2025.01.26 |