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;
#ifdef LOCAL
#include "dbg.h"
#else
#define dbg(...)
#endif
#define sz(s) (int)(s).size()
#define all(x) (x).begin(), (x).end()
typedef long long ll;
const int inf = INT_MAX;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
queue<int> mp[200042];
inline int fix(int x)
{
if (x < 0)
x = 100000 - x;
return x;
}
ll count_swaps(vector<int> S)
{
int n = sz(S);
ll ans = 0;
//unordered_map<int, queue<int>> mp;
for (int i = 0; i < n; i++)
{
mp[fix(S[i])].push(i);
}
vector<int> offset(n);
for (int i = 0; i < n;)
{
if (S[i] == inf)
{
i++;
continue;
}
vector<array<int, 3>> best; // best[i] = {left_index, right_index, swap_count}
int j = mp[fix(-S[i])].front();
if (S[i] < 0)
best.push_back({i, j, j - i - 1});
else
best.push_back({j, i, j - i});
i++;
if (abs(S[i]) != abs(S[i-1]))
{
if (S[i] < 0)
best.push_back({i, j, j - i + 1});
else
best.push_back({j, i, j - i + 2});
}
i--;
sort(best.begin(), best.end(), [](auto &x, auto &y) { return x[2] < y[2]; });
auto [x, y, z] = best[0];
ans += z - offset[i] + offset[j];
if (min(x, y) == i + 1)
offset[i] += 2;
if (i + 1 <= j - 1)
{
for (int k = i + 1; k <= j - 1; k++)
offset[k]++;
}
mp[fix(S[x])].pop();
mp[fix(S[y])].pop();
S[x] = inf;
S[y] = inf;
}
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... |