이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define mp make_pair
int n;
vector<int> val;
vector<int> diff; // diff[i] = value(i) - value(i - 1)
vector<int> segtree;
int range_query(int v, int vl, int vr, int ql, int qr) {
if(ql > vr || qr < vl) {
return 0;
}
if(vl == ql && vr == qr) {
return segtree[v];
}
int mid = (vl + vr) / 2;
return range_query(2 * v, vl, mid, ql, min(qr, mid))
+ range_query(2 * v + 1, mid + 1, vr, max(ql, mid + 1), qr);
}
int query(int pos) {
return range_query(1, 1, 2 * n + 1, 1, pos);
}
void point_update(int v, int vl, int vr, int pos, int add) {
if(vl == vr) {
segtree[v] += add;
} else {
int mid = (vl + vr) / 2;
if(pos <= mid) {
point_update(2 * v, vl, mid, pos, add);
} else {
point_update(2 * v + 1, mid + 1, vr, pos, add);
}
segtree[v] = segtree[2 * v] + segtree[2 * v + 1];
}
}
void update(int l, int r, int add) {
point_update(1, 1, 2 * n + 1, l, add);
point_update(1, 1, 2 * n + 1, r + 1, -add);
}
int solve() {
int ans = 0;
diff.assign(1 + 2 * n + 1, 0);
segtree.assign(1 + 4 * (2 * n + 1), 0);
vector<int> where(1 + 2 * n, 0);
vector<int> nxt(1 + 2 * n, 0);
vector<int> cur_pos(1 + n, 0);
for(int i = 2 * n; i >= 1; i--) {
if(val[i] > 0) {
nxt[i] = cur_pos[val[i]];
cur_pos[val[i]] = i;
}
}
int cnt = 0;
for(int i = 1; i <= 2 * n; i++) {
if(val[i] < 0) {
int par=cur_pos[-val[i]];
//cout << i << ": " << ans << " ";
cnt++;
ans += (i + query(i)) - (2 * cnt - 1);
//cout << ans << " ";
// upd between 2 * cnt - 1 and i
update(1, i, 1);
ans += (par + query(par)) - (2 * cnt);
//cout << ans << "\n";
// upd between 2 * cnt and par
update(1, par, 1);
cur_pos[-val[i]] = nxt[par];
}
}
return ans;
}
long long count_swaps(vector<signed> s) {
n = s.size() / 2;
val.pb(0);
for(int i = 0; i < 2 * n; i++) {
val.pb(s[i]);
}
return solve();
}
/*
signed main()
{
int n;
vector<signed> x;
cin >> n;
for (int i=0; i<2*n; i++) {
int a; cin >> a;
x.push_back(a);
}
cout << count_swaps(x);
return 0;
}
*/
/*
3
-1 -3 2 3 -2 1
*/
# | 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... |