Advertisement
Josif_tepe

Untitled

Jun 10th, 2023
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4. #include <map>
  5. using namespace std;
  6. typedef long long ll;
  7. const int maxn = 1e6 + 10;
  8. int a[maxn];
  9. ll segment_tree[3 * maxn];
  10. void build_tree(int L, int R, int pos) {
  11.     if(L == R) {
  12.         segment_tree[pos] = 0;
  13.     }
  14.     else {
  15.         int middle = (L + R) / 2;
  16.         build_tree(L, middle, 2 * pos);
  17.         build_tree(middle + 1, R, 2 * pos + 1);
  18.         segment_tree[pos] = segment_tree[2 * pos] + segment_tree[2 * pos + 1];
  19.     }
  20. }
  21. ll query(int L, int R, int pos, int i, int j) {
  22.     // R i L R j L
  23.     if(i <= L and R <= j) {
  24.         return segment_tree[pos];
  25.     }
  26.     if(R < i or j < L) {
  27.         return 0;
  28.     }
  29.     int mid = (L + R) / 2;
  30.     return query(L, mid, 2 * pos, i, j) + query(mid + 1, R, 2 * pos + 1, i, j);
  31. }
  32. void update(int L, int R, int pos, int idx, int new_val) {
  33.     if(L == R) {
  34.         segment_tree[pos] += new_val;
  35.         return;
  36.     }
  37.     int mid = (L + R) / 2;
  38.     if(idx <= mid) {
  39.         update(L, mid, 2 * pos, idx, new_val);
  40.     }
  41.     else {
  42.         update(mid + 1, R, 2 * pos + 1, idx, new_val);
  43.     }
  44.     segment_tree[pos] = segment_tree[2 * pos] + segment_tree[2 * pos + 1];
  45. }
  46.  
  47. int main() {
  48.     ios_base::sync_with_stdio(false);
  49.     int n;
  50.     cin >> n;
  51.     for(int i = 0; i < n; i++) {
  52.         cin >> a[i];
  53.     }
  54.     build_tree(0, n - 1, 1);
  55.     map<int, int> cnt;
  56.     vector<ll> freq(n, 0);
  57.     for(int i = 0; i < n; i++) {
  58.         cnt[a[i]]++;
  59.         freq[i] = cnt[a[i]];
  60.     }
  61.     map<int, int> cnt2;
  62.     ll result = 0;
  63.     for(int i = n - 1; i >= 0; i--) {
  64.         result += query(0, n - 1, 1, 0, freq[i] - 1);
  65.         cnt2[a[i]]++;
  66.         update(0, n - 1, 1, cnt2[a[i]], 1);
  67.     }
  68.     cout << result << endl;
  69.     return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement