Submission #831757

#TimeUsernameProblemLanguageResultExecution timeMemory
831757finn__Ancient Books (IOI17_books)C++17
50 / 100
1408 ms55088 KiB
#include "books.h"
#include <bits/stdc++.h>
using namespace std;
using L = long long;

long long minimum_walk(std::vector<int> p, int s)
{
    size_t const n = p.size();
    L ans = 0;
    for (int i = 0; i < n; ++i)
        ans += abs(i - p[i]);

    set<int> unexplored;
    for (int i = 0; i < n; ++i)
        if (p[i] != i)
            unexplored.insert(i);

    int a = s, b = s;

    auto explore_cycle = [&](int u)
    {
        auto it = unexplored.find(u);
        while (it != unexplored.end())
        {
            a = min(a, u);
            b = max(b, u);
            u = p[u];
            unexplored.erase(it);
            it = unexplored.find(u);
        }
    };

    explore_cycle(s);
    while (!unexplored.empty())
    {
        auto it = unexplored.lower_bound(a);
        if (it != unexplored.end() && *it <= b)
        {
            explore_cycle(*it);
        }
        else
        {
            if (it != unexplored.end())
            {
                ans += 2 * (*it - b);
                explore_cycle(*it);
            }
            else
            {
                --it;
                ans += 2 * (a - *it);
                explore_cycle(*it);
            }
        }
    }

    return ans;
}

Compilation message (stderr)

books.cpp: In function 'long long int minimum_walk(std::vector<int>, int)':
books.cpp:10:23: warning: comparison of integer expressions of different signedness: 'int' and 'const size_t' {aka 'const long unsigned int'} [-Wsign-compare]
   10 |     for (int i = 0; i < n; ++i)
      |                     ~~^~~
books.cpp:14:23: warning: comparison of integer expressions of different signedness: 'int' and 'const size_t' {aka 'const long unsigned int'} [-Wsign-compare]
   14 |     for (int i = 0; i < n; ++i)
      |                     ~~^~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...