1268C - K Integers - CodeForces Solution


binary search data structures *2300

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
// Ofast, O0, O1, O2, O3, unroll-loops, fast-math, trapv

typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;

#define Mp          make_pair
#define sep         ' '
#define endl        '\n'
#define F	        first
#define S	        second
#define pb          push_back
#define all(x)      (x).begin(),(x).end()
#define kill(res)	cout << res << '\n', exit(0);
#define set_dec(x)	cout << fixed << setprecision(x);
#define fast_io     ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define file_io     freopen("input.txt", "r", stdin) ; freopen("output.txt", "w", stdout);

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const ll L = 20;
const ll N = 2e5 + 50;
const ll Mod = 1e9 + 7;

ll n, arr[N], idx[N], inv[N], mid[N], bit[N];

void upd(int x, int y = 1){
    for(; x <= n; x += x & (-x)) bit[x] += y;
}

ll get(int x){
    ll out = 0;
    for(; x; x &= x-1) out += bit[x];
    return out;
}

ll fst(ll x){
    ll sum = 0, pos = 0;
    for(int i = L-1; i >= 0; i--){
        if(pos + (1 << i) <= n && sum + bit[pos + (1 << i)] < x){
            pos += (1 << i); sum += bit[pos];
        }
    }
    return pos+1;
}

ll c2(ll x){
    return x * (x+1) / 2;
}

int main(){
    fast_io;

    cin >> n;

    for(int i = 1; i <= n; i++){
        cin >> arr[i]; idx[arr[i]] = i;
    }

    for(int i = 1; i <= n; i++){
        inv[i] = inv[i-1] + i - get(idx[i]) - 1; upd(idx[i]);
        mid[i] = fst((i+1)/2);
    }

    fill(bit, bit+N, 0);
    
    ll sum = 0;
    for(int i = 1; i <= n; i++){
        upd(idx[i], idx[i]); sum += idx[i];

        ll res = inv[i] + ((i+1) / 2 * mid[i] - get(mid[i]) - c2((i+1) / 2 - 1)) + (sum - get(mid[i]) - i/2 * mid[i] - c2(i/2));
        cout << res << sep;
    }

}


Comments

Submit
0 Comments
More Questions

946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary