Official

E - 荷物の集積作業 / Cargo Accumulation Work Editorial by MMNMM Editorial for printing


\(i\) 回目の作業で荷物の移動の対象となる(区間 \([L _ i,R _ i]\) に含まれ、荷物が \(1\) つ以上置かれている)倉庫の個数を \(p _ i\) とします。 この作業で、荷物が \(1\) つ以上置かれている倉庫は少なくとも \(\max\lbrace p _ i-2,0\rbrace\) 個減少します(区間 \([L _ i,R _ i]\) に含まれる荷物が \(1\) つ以上置かれている倉庫は \(p _ i\) 個からたかだか \(2\) 個になります)。

はじめ、荷物が \(1\) つ以上置かれている倉庫は \(N\) 個以下で、すべての作業が終わったあと荷物が \(1\) つ以上置かれている倉庫は \(0\) 個以上です。 よって、\(\displaystyle\sum _ {i=0} ^ Qp _ i=2Q+\sum _ {i=0} ^ Q(p _ i-2)\le2Q+N\) が成り立ちます。

よって、\(i\) 回目の操作を \(O(p _ i)\) や \(O(p _ i\log N)\) 時間などで処理することができれば、全体で \(O(N+Q)\) 時間や \(O((N+Q)\log N)\) 時間などになります。

これは、荷物が \(1\) つ以上置かれている倉庫の位置と荷物の個数を平衡二分探索木などで管理することで実現できます。

倉庫 \(i\) の現在の荷物の個数 \(A _ i\) と \(iA _ i\) の \(2\) 種類の区間和・区間更新を処理することなどでもこの問題を解くことができます。

実装例は以下のようになります。

#include <iostream>
#include <set>
using namespace std;

int main() {
    int N, Q;
    cin >> N >> Q;

    // 1 個以上の荷物が置かれている倉庫の (位置, 個数)
    set<pair<int, long>> store;
    for (int i = 1; i <= N; ++i) {
        int A;
        cin >> A;
        if (A > 0) {
            store.emplace(i, A);
        }
    }

    for (int i = 0; i < Q; ++i) {
        int L, R;
        cin >> L >> R;

        long cost = 0;
        long L_count = 0, R_count = 0;
        // 区間内の倉庫を走査
        auto it = store.lower_bound({L, 0});
        while (it != store.end() && it->first <= R) {
            cost += min(it->first - L, R - it->first) * it->second;
            if (it->first - L <= R - it->first) {
                L_count += it->second;
            } else {
                R_count += it->second;
            }
            it = store.erase(it);
        }

        if (L_count > 0) {
            store.emplace(L, L_count);
        }
        if (R_count > 0) {
            store.emplace(R, R_count);
        }
        cout << cost << endl;
    }
    return 0;
}
from sortedcontainers import SortedSet


N, Q = map(int, input().split())

# 1 個以上の荷物が置かれている倉庫の (位置, 個数)
store = SortedSet()
for i, A in enumerate(map(int, input().split())):
    if A > 0:
        store.add((i + 1, A))

for i in range(Q):
    L, R = map(int, input().split())

    cost = 0
    L_count = 0
    R_count = 0
    # 区間内の倉庫を走査
    id = store.bisect_left((L, 0))
    while id < len(store) and store[id][0] <= R:
        cost += min(store[id][0] - L, R - store[id][0]) * store[id][1]
        if store[id][0] - L <= R - store[id][0]:
            L_count += store[id][1]
        else:
            R_count += store[id][1]
        store.remove(store[id])

    if L_count > 0:
        store.add((L, L_count))
    if R_count > 0:
        store.add((R, R_count))

    print(cost)

posted:
last update: