#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Fenwick {
int n;
vector<ll> bit;
Fenwick(int n) : n(n), bit(n + 1, 0) {}
void update(int idx, ll val) {
for (++idx; idx <= n; idx += idx & -idx)
bit[idx] += val;
}
ll query(int idx) {
ll sum = 0;
for (++idx; idx > 0; idx -= idx & -idx)
sum += bit[idx];
return sum;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> H(n);
for (int i = 0; i < n; i++)
cin >> H[i];
// Coordinate compression
vector<int> sorted = H;
sort(sorted.begin(), sorted.end());
sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
for (int i = 0; i < n; i++) {
H[i] = lower_bound(sorted.begin(), sorted.end(), H[i]) - sorted.begin();
}
Fenwick fenwLeft(sorted.size());
vector<ll> leftSmaller(n);
// Count smaller on left
for (int i = 0; i < n; i++) {
leftSmaller[i] = fenwLeft.query(H[i] - 1);
fenwLeft.update(H[i], 1);
}
Fenwick fenwRight(sorted.size());
vector<ll> rightSmaller(n);
// Count smaller on right
for (int i = n - 1; i >= 0; i--) {
rightSmaller[i] = fenwRight.query(H[i] - 1);
fenwRight.update(H[i], 1);
}
ll ans = 0;
for (int i = 0; i < n; i++) {
ans += leftSmaller[i] * rightSmaller[i];
}
cout << ans << "\n";
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |