알고리즘
백준 6198번 옥상 정원 꾸미기 C++
영춘권의달인
2022. 3. 21. 17:41
스택 자료구조를 이용해서 문제를 해결하였다.
스택을 쌓을때 크기가 작아지도록만 쌓이게 하고 하나 쌓았을 때 전에 있던 모든 빌딩들이 지금 쌓은 옥상을 확인할 수 있으므로 스택의 사이즈 - 1을 더해준다.
만약 지금 top보다 큰 빌딩이 오면 스택의 top이 빌딩보다 커질때까지 pop을 해준다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
ll ans = 0;
stack<int> st;
for (int i = 0; i < n; i++) {
int h;
cin >> h;
if (st.empty()) {
st.push(h);
}
else {
if (st.top() <= h) {
while (st.top() <= h) {
st.pop();
if (st.empty()) break;
}
}
st.push(h);
}
ans += st.size() - 1;
}
cout << ans;
};