스택(Stack)
백준 3015번: 오아시스 재결합
cepiloth
2018. 7. 1. 18:46
반응형
https://www.acmicpc.net/problem/3015
1. 문제
오아시스의 재결합 공연에 N명이 한 줄로 서서 기다리고 있다. 이 역사적인 순간을 맞이하기 위해 줄에서서 기다리고 있던 백준이는 갑자기 자기가 볼 수 있는 사람의 수가 궁금해 졌다. 두 사람 A와 B가 서로 볼 수 있으려면, 두 사람 사이에 A 또는 B보다 키가 큰 사람이 없어야 한다. 줄에 서있는 사람의 키가 주어졌을 때, 서로 볼 수 있는 쌍의 수를 구하는 프로그램을 작성하시오.
2. 알고리즘
키워드 - 스택
3. 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <functional> #include <vector> #include <list> #include <queue> #include <deque> #include <map> #include <set> #include <stack> using namespace std; #define MAX_SIZE 100 #define INF 0x7fffffff #define CENDL "\n" /* * @memory - 2380 kb * @time - 56 ms */ int main() { cin.tie(0); std::ios::sync_with_stdio(false); int n; cin >> n; stack<pair<int, int>> st; long long sol = 0; while(n--) { int d; cin >> d; while( !st.empty() && st.top().first < d) { sol += st.top().second; st.pop(); } if( !st.empty() ) { if( st.top().first == d ) { pair<int, int> topElement = st.top(); st.pop(); sol += (topElement.second); if( !st.empty() ) { sol += 1; } topElement.second += 1; st.push(topElement); } else { pair<int, int> newElement(d, 1); sol += 1; st.push(newElement); } } else { pair<int, int> newElement(d, 1); st.push(newElement); } } cout << sol << "\n"; return 0; } | cs |
반응형