#include #include #include #include #include #include #include using namespace std; typedef long long ll; map mp_min, mp_max; int N; int p[100000]; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; cin >> N; for(int i = 0; i < N; i++) cin >> p[i]; mp_min[p[0]] = 1; mp_max[p[0]] = 1; ll ans = 0; for(int i = 1; i < N; i++){ auto ptr = mp_min.lower_bound(p[i]); ll sum = 0; vector buf; for(auto iter = ptr; iter != mp_min.end(); iter++){ sum += iter->second; buf.push_back(iter->first); } for(int j : buf) mp_min.erase(j); ans += sum; mp_min[p[i]] = sum+1; sum = 0; ptr = mp_max.lower_bound(p[i]); for(auto iter = mp_max.begin(); iter != ptr; iter++){ sum += iter->second; buf.push_back(iter->first); } for(int j : buf) mp_max.erase(j); ans += sum; mp_max[p[i]] = sum+1; } cout << ans << endl; }