이 문제의 핵심은 "같은 키를 가진 사람들을 어떻게 처리할 것인가?" 이다. 스택에 push할 때 같은 키를 가진 사람이 몇명 연속돼있는지 함께 기록한다.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
stack<pair<int, int>> s;
int n;
long long sz, ans = 0;
cin >> n;
while (n--) {
int x;
cin >> x;
pair<int, int> p = {x, 1};
while (!s.empty() && s.top().first < x) {
sz = s.top().second;
s.pop();
if (!s.empty()) {
ans += sz;
}
ans += sz;
ans += sz*(sz-1)/2;
}
if (!s.empty() && s.top().first == x) {
pair<int, int> p = {x, s.top().second+1};
s.pop();
s.push(p);
}
else {
s.push(p);
}
}
while (!s.empty()) {
sz = s.top().second;
s.pop();
if (!s.empty()) {
ans += sz;
}
ans += sz*(sz-1)/2;
}
cout << ans;
return 0;
}
어제 하루종일 헤딩한 문제인데 오늘 풀려서 기분이 상당히 좋다. pair랑 2칸짜리 array 둘 다 써봤는데 시간차이가 별로 안난다.