먼저 스택을 다 받은뒤
이후 스택에 pop과 top을 사용해서 vector에 push_back하여 넣고
vector에 넣은 값과 현재 스택의 top값을 계산해서 어떤것이 더 큰지 계산하려고 구현

실패한 코드
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, h, cnt = 0, total = 0;
cin >> n;
stack<int> stk;
vector<int> vec;
for (int i = 0; i < n; i++) {
cin >> h;
stk.push(h); //스택값 받기
}
int k;
for (int i = 0; i < n; i++) {
cnt = 0; //카운팅 초기화
k = stk.top(); //임의로 빌딩 높이값 받기
if (i == 0) { //첫번째 루프일때 백터에 스택 top값 넣기
vec.push_back(stk.top());
stk.pop(); // 스택 뺴기
continue;
}
int vs = vec.size();
while (vs--) {//임의 값보다 이전 빌딩의 높이가 낮을 때까지
if (k > vec[vs]) cnt++; //오른쪽으로 볼수있는 빌딩 갯수 카운팅
}
total += cnt;
vec.push_back(stk.top());
stk.pop();
}
cout << total;
}
정답 코드
출처 : https://programforlife.tistory.com/53
#include <iostream>
#include <stack>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int count;
stack<int> stk;
long long answer = 0;
cin >> count;
for (int i = 0; i < count; i++) {
int height;
cin >> height;
//1. 첫번째 건물은 바로 스택에 넣어줌
if (stk.empty()) { stk.push(height); continue; }
//2. i) 스택에 있는 건물들 중에, 현재 건물 보다 작은 건물들은 다 빼줍니다.
while (!stk.empty() && stk.top() <= height)
stk.pop();
//2. ii) 건물을 다 빼줬으면, 스택에 있는 개수만큼 답에 더해줍니다.
answer += stk.size();
//2. iii) 해당 입력을 스택에 넣어줍니다.
stk.push(height);
}
cout << answer;
}