# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
748838 | wenqi | Ancient Books (IOI17_books) | C++17 | 1 ms | 292 KiB |
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 "books.h"
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
using ll = long long;
bool seen[1000005];
vector<int> P;
vector<int> t;
ll dfs(int i)
{
if (seen[i])
return 0;
seen[i] = true;
t.push_back(i);
return abs(i - P[i]) + dfs(P[i]);
}
ll minimum_walk(vector<int> p, int s)
{
P = p;
ll sum = 0;
int n = p.size();
vector<vector<int>> q;
multiset<int> ms;
int mx = 0;
priority_queue<pair<int, pair<int, int>>> pq;
for (int i = 0; i < n; i++)
{
if (seen[i] or i == p[i])
continue;
t.clear();
sum += dfs(i);
sort(t.begin(), t.end());
pq.push({-t[0], {q.size(), 0}});
q.push_back(t);
ms.insert(t[0]);
mx = max(mx, t[0]);
}
if (q.empty())
return sum;
ll ans = 1e18;
while (true)
{
auto [x, pr] = pq.top();
auto [a, b] = pr;
pq.pop();
int w = *ms.begin();
ans = min(ans, sum + 2 * max(0, s - w) + 2 * max(0, mx - s));
if (q[a].size() - 1 == b)
break;
ms.erase(ms.find(-x));
int h = q[a][++b];
ms.insert(h);
mx = max(mx, h);
pq.push({-h, {a, b}});
}
return ans;
}
Compilation message (stderr)
# | 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... |