結果

問題 No.1028 闇討ち
コンテスト
ユーザー kuhaku
提出日時 2026-04-14 10:14:21
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 254 ms / 2,000 ms
コード長 1,895 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,335 ms
コンパイル使用メモリ 204,312 KB
実行使用メモリ 16,512 KB
最終ジャッジ日時 2026-04-14 10:14:32
合計ジャッジ時間 5,479 ms
ジャッジサーバーID
(参考情報)
judge2_1 / judge3_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

// competitive-verifier: PROBLEM https://yukicoder.me/problems/no/1028
#include <iostream>
#include <vector>
#include <algorithm>
#include <concepts>
#include <functional>
#include <queue>
/// @brief slope trick
template <class T>
struct slope_trick {
    slope_trick() = default;
    [[nodiscard]] T min_x() const { return l.top(); }
    [[nodiscard]] T min_value() const { return min_f; }
    /// @brief Add f(x) = a
    void add_const(T a) { min_f += a; }
    /// @brief Add f(x) = max(0, x - a)
    void add_x_minus_a(T a) {
        if (!l.empty() && l.top() > a) {
            min_f += l.top() - a;
        }
        l.push(a);
        r.push(l.top());
        l.pop();
    }
    /// @brief Add f(x) = max(0, a - x)
    void add_a_minus_x(T a) {
        if (!r.empty() && a > r.top()) {
            min_f += a - r.top();
        }
        r.push(a);
        l.push(r.top());
        r.pop();
    }
    /// @brief Add f(x) = abs(x - a) = max(0, x - a) + max(0, a - x)
    void add_abs(T a) {
        add_x_minus_a(a);
        add_a_minus_x(a);
    }
    /// @brief f(x) <- min_{y <= x} f(y)
    void clear_right() { r = decltype(r)(); }
    /// @brief f(x) <- min_{y >= x} f(y)
    void clear_left() { l = decltype(l)(); }
  private:
    T min_f{};
    std::priority_queue<T> l;
    std::priority_queue<T, std::vector<T>, std::greater<T>> r;
};
int main(void) {
    int n;
    std::cin >> n;
    std::vector a(n, std::vector(n, 0));
    for (auto& v : a) {
        for (auto& e : v) std::cin >> e;
    }
    std::vector<slope_trick<int>> v(n);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            v[a[i][j] - 1].add_const(j);
            v[a[i][j] - 1].add_x_minus_a(i + j);
            v[a[i][j] - 1].add_a_minus_x(i - j);
        }
    }
    int ans = 0;
    for (int i = 0; i < n; ++i) ans += v[i].min_value();
    std::cout << ans << '\n';
    return 0;
}
0