제출 #1339930

#제출 시각아이디문제언어결과실행 시간메모리
1339930lazyArranging Shoes (IOI19_shoes)C++20
100 / 100
159 ms140624 KiB
#include <bits/stdc++.h>
using namespace std;

#define lazy ios::sync_with_stdio(false); cin.tie(nullptr);

const int OFFSET = 100000;
vector<int> tree;

void build(int node, int l, int r) {
    if (l == r) {
        tree[node] = 1;
        return;
    }
    int mid = l + (r - l) / 2;
    build(2 * node, l, mid);
    build(2 * node + 1, mid + 1, r);
    tree[node] = tree[2 * node] + tree[2 * node + 1];
}

void update(int node, int l, int r, int idx, int val) {
    if (l == r) {
        tree[node] = val;
        return;
    }
    int mid = l + (r - l) / 2;
    if (idx <= mid) update(2 * node, l, mid, idx, val);
    else update(2 * node + 1, mid + 1, r, idx, val);
    tree[node] = tree[2 * node] + tree[2 * node + 1];
}

int query(int node, int l, int r, int ql, int qr) {
    if (ql > r || qr < l) return 0;
    if (ql <= l && r <= qr) return tree[node];
    int mid = l + (r - l) / 2;
    return query(2 * node, l, mid, ql, qr) + query(2 * node + 1, mid + 1, r, ql, qr);
}

long long count_swaps(vector<int> S) {
    int n = S.size() / 2;

    tree.assign(8 * n, 0);
    build(1, 0, 2 * n - 1);

    vector<queue<int>> pos(200005);
    for (int i = 0; i < 2 * n; i++) {
        pos[S[i] + OFFSET].push(i);
    }

    vector<bool> visited(2 * n, false);
    long long total_swaps = 0;

    for (int i = 0; i < 2 * n; i++) {
        if (visited[i]) continue;

        visited[i] = true;
        pos[S[i] + OFFSET].pop();

        int target_shoe = -S[i];
        int j = pos[target_shoe + OFFSET].front();
        pos[target_shoe + OFFSET].pop();
        visited[j] = true;

        int unvisited_between = 0;
        if (i + 1 <= j - 1) {
            unvisited_between = query(1, 0, 2 * n - 1, i + 1, j - 1);
        }

        if (S[i] < 0) {
            total_swaps += unvisited_between;
        } else {
            total_swaps += unvisited_between + 1;
        }

        update(1, 0, 2 * n - 1, i, 0);
        update(1, 0, 2 * n - 1, j, 0);
    }

    return total_swaps;
}

#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...
#Verdict Execution timeMemoryGrader output
Fetching results...