/** * author: ivanzuki * created: Fri Sep 24 2021 **/ #include using namespace std; string to_string(string s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } template string to_string(pair p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } void debug_out() { cerr << endl; } template void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } template void dout(string name, int idx, T arg) { cerr << name << " = " << to_string(arg); } template void dout(string names, int idx, T1 arg, T2... args) { cerr << names.substr(0, names.find(',')) << " = " << to_string(arg) << ", "; dout(names.substr(names.find(',') + 2), idx + 1, args...); } #ifdef LOCAL #define debug(...) cerr << "[", dout(#__VA_ARGS__, 0, __VA_ARGS__), cerr << "]" << endl; #else #define debug(...) 42 #endif int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector p(n); set s; for (int i = 0; i < n; i++) { cin >> p[i]; --p[i]; s.insert(i); } if (n == 2 && p[0] == 0) { cout << 0 << '\n'; return 0; } vector ans(n, -1); for (int i = n - 1; i >= 0; i--) { auto it = s.upper_bound(p[i]); if (it != s.end()) { ans[i] = *it; s.erase(it); } } for (int i = n - 1; i >= 0; i--) { if (ans[i] == -1) { auto it = s.lower_bound(p[i]); if (it == s.end()) { --it; } ans[i] = *it; } } debug(ans); long long res = 0; for (int i = 0; i < n; i++) { if (ans[i] > p[i]) { res += i + 1; } else if (ans[i] < p[i]) { res -= i + 1; } } cout << res << '\n'; return 0; }