// _ _ _ _
//| | __ _ _____ _| | ___| |_| |_ _ _ ___ ___
//| |/ _` |_ / | | | |/ _ \ __| __| | | |/ __/ _ \lazylettuce
//| | (_| |/ /| |_| | | __/ |_| |_| |_| | (_| __/
//|_|\__,_/___|\__, |_|\___|\__|\__|\__,_|\___\___|
// |___/
#include<bits/stdc++.h>
using namespace std;
using ll =long long ;
int MOD1=998244353;
int MOD2=1e9+7;
struct Fenwick {
int n;
vector<ll> bit;
Fenwick(int n_ = 0) { init(n_); }
void init(int n_) { n = n_; bit.assign(n+1, 0); }
void update(int idx, ll delta = 1) {
if (idx <= 0) return;
for (; idx <= n; idx += idx & -idx) bit[idx] += delta;
}
ll query(int idx) {
if (idx <= 0) return 0;
ll res = 0;
for (; idx > 0; idx -= idx & -idx) res += bit[idx];
return res;
}
ll total() { return query(n); }
ll inv_count(const vector<int>& v) {
fill(bit.begin(), bit.end(), 0);
ll inv = 0;
for (int x : v) {
if (x < 1 || x > n) {
// skip bad indices (defensive)
continue;
}
inv += (total() - query(x));
update(x, 1);
}
return inv;
}
};
long long count_swaps(std::vector<int> S) {
int m = S.size();
std::map<int, std::set<int>> left_indices, right_indices;
for (int i = 0; i < m; i++) {
if (S[i] < 0) {
left_indices[abs(S[i])].insert(i + 1);
} else {
right_indices[abs(S[i])].insert(i + 1);
}
}
std::vector<int> temp;
for (int i = 0; i < m; ++i) {
if (S[i] < 0) {
int mag = abs(S[i]);
auto it = right_indices[mag].begin();
int right_partner_idx = *it;
temp.push_back(i + 1);
temp.push_back(right_partner_idx);
right_indices[mag].erase(it);
}
}
Fenwick f(m);
ll ans = f.inv_count(temp);
return ans;
}
# | 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... |