This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
const ll inf = 1e9;
const int md1 = 1e9+7;
const int md2 = 998244353;
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define sz(v) ((int)v.size())
#define forn(i,n) for(int i = 0; i < n; ++i)
#define forbe(i,b,e) for(int i = b; i < e; ++i)
#define pb push_back
#define pry puts("YES")
#define prn puts("NO")
#define endl '\n'
#define fst first
#define scn second
const int N = 1e5;
bitset<N> c;
int pnt[N+1];
template<typename T>
struct BIT{
int n;
vector<T> fen;
BIT(int n){
this->n = n;
fen.assign(n,0);
}
BIT(vector<T> a) : BIT(a.size()){
for(int i = 0; i < n; ++i) add(i,a[i]);
}
void add(int x, T v){
for(; x < n; x |= x+1) fen[x] += v;
}
T query(int x){
T res = 0;
for(; x >= 0; x = (x&(x+1))-1)
res += fen[x];
return res;
}
T query(int l, int r){
return query(r) - query(l-1);
}
};
ll
count_swaps(vector<int> s)
{
ll ans = 0;
int balance[sz(s)+1];
vector<int> npos(sz(s),-1);
vector<int> lpos(sz(s),-1);
vector<int> spos(sz(s)+1,-1);
vector<int> sspos(sz(s)+1,-1);
for (int i = 0; i < sz(s); ++i) balance[i+1] = 0;
int size;
BIT<int> deltr(sz(s)/2+5);
for (int i = 0; i < sz(s); ++i) {
size = abs(s[i]);
if (s[i] > 0) {
if (balance[size] < 0) {
c[i] = 1;
npos[spos[size]] = i;
spos[size] = lpos[spos[size]];
} else {
if (spos[size] == -1) {
spos[size] = i;
sspos[size] = i;
} else {
lpos[sspos[size]] = i;
}
}
++balance[size];
} else {
if (balance[size] > 0) {
c[i] = 1;
npos[spos[size]] = i;
spos[size] = lpos[spos[size]];
} else {
if (spos[size] == -1) {
spos[size] = i;
sspos[size] = i;
} else {
lpos[sspos[size]] = i;
}
}
--balance[size];
}
}
for (int i = 0; i < sz(s); ++i) {
if (c[i]) continue;
size = abs(s[i]);
if (s[i] < 0)
--ans;
ans += npos[i] - i - deltr.query(i,npos[i]);
deltr.add(npos[i],1);
}
return ans;
}
#ifdef ONPC
void
solve()
{
int n;
cin >> n;
vector<int> s(n);
for (int i = 0; i < n; ++i)
cin >> s[i];
cout <<count_swaps(s) << endl;
}
int32_t
main()
{
freopen("in", "r", stdin);
int t = 1;
/* cin >> t; */
while(t--)
solve();
}
#endif
# | 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... |