Новая Школа - онлайн-школа подготовки к ЕГЭ
Задача · 9 класс Задача №3652741
А
Аноним
14 сентября 2026 04:44 · публичный вопрос
А
Аноним

Реши задание на изображении

Ответ нейросети

Решение на C++17:

#include <bits/stdc++.h>
using namespace std;

struct Gap {
    int l, r, x, dist, order;
};

struct Cmp {
    bool operator()(const Gap& a, const Gap& b) const {
        if (a.dist != b.dist) return a.dist < b.dist;
        return a.order > b.order;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> p(n + 1), pos(n + 1);
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
        pos[p[i]] = i;
    }

    priority_queue<Gap, vector<Gap>, Cmp> q;

    auto addGap = [&](int l, int r) {
        if (l == 0) {
            if (r > 1)
                q.push({l, r, 1, r - 1, pos[1]});
        } else if (r == n + 1) {
            if (l < n)
                q.push({l, r, n, n - l, pos[n]});
        } else if (r - l > 1) {
            int d = r - l;
            int x1 = l + d / 2;
            int x2 = l + (d + 1) / 2;
            int x = (pos[x1] <= pos[x2]) ? x1 : x2;
            q.push({l, r, x, d / 2, pos[x]});
        }
    };

    vector<int> ans;
    ans.reserve(n);

    int first = p[1];
    ans.push_back(first);

    if (first > 1) addGap(0, first);
    if (first < n) addGap(first, n + 1);

    for (int i = 1; i < n; ++i) {
        Gap g = q.top();
        q.pop();

        ans.push_back(g.x);

        if (g.l == 0)
            addGap(g.x, g.r);
        else if (g.r == n + 1)
            addGap(g.l, g.x);
        else {
            addGap(g.l, g.x);
            addGap(g.x, g.r);
        }
    }

    for (int i = 0; i < n; ++i) {
        if (i) cout << ' ';
        cout << ans[i];
    }

    return 0;
}