Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cstring>
- #include <map>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e6 + 10;
- int a[maxn];
- ll segment_tree[3 * maxn];
- void build_tree(int L, int R, int pos) {
- if(L == R) {
- segment_tree[pos] = 0;
- }
- else {
- int middle = (L + R) / 2;
- build_tree(L, middle, 2 * pos);
- build_tree(middle + 1, R, 2 * pos + 1);
- segment_tree[pos] = segment_tree[2 * pos] + segment_tree[2 * pos + 1];
- }
- }
- ll query(int L, int R, int pos, int i, int j) {
- // R i L R j L
- if(i <= L and R <= j) {
- return segment_tree[pos];
- }
- if(R < i or j < L) {
- return 0;
- }
- int mid = (L + R) / 2;
- return query(L, mid, 2 * pos, i, j) + query(mid + 1, R, 2 * pos + 1, i, j);
- }
- void update(int L, int R, int pos, int idx, int new_val) {
- if(L == R) {
- segment_tree[pos] += new_val;
- return;
- }
- int mid = (L + R) / 2;
- if(idx <= mid) {
- update(L, mid, 2 * pos, idx, new_val);
- }
- else {
- update(mid + 1, R, 2 * pos + 1, idx, new_val);
- }
- segment_tree[pos] = segment_tree[2 * pos] + segment_tree[2 * pos + 1];
- }
- int main() {
- ios_base::sync_with_stdio(false);
- int n;
- cin >> n;
- for(int i = 0; i < n; i++) {
- cin >> a[i];
- }
- build_tree(0, n - 1, 1);
- map<int, int> cnt;
- vector<ll> freq(n, 0);
- for(int i = 0; i < n; i++) {
- cnt[a[i]]++;
- freq[i] = cnt[a[i]];
- }
- map<int, int> cnt2;
- ll result = 0;
- for(int i = n - 1; i >= 0; i--) {
- result += query(0, n - 1, 1, 0, freq[i] - 1);
- cnt2[a[i]]++;
- update(0, n - 1, 1, cnt2[a[i]], 1);
- }
- cout << result << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement