結果

問題 No.924 紲星
ユーザー iiljjiiljj
提出日時 2020-11-12 20:56:16
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 796 ms / 4,000 ms
コード長 18,559 bytes
コンパイル時間 2,684 ms
コンパイル使用メモリ 228,804 KB
実行使用メモリ 26,412 KB
最終ジャッジ日時 2024-07-22 19:47:18
合計ジャッジ時間 10,107 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 2 ms
6,944 KB
testcase_02 AC 2 ms
6,944 KB
testcase_03 AC 3 ms
6,944 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 4 ms
6,940 KB
testcase_06 AC 3 ms
6,940 KB
testcase_07 AC 3 ms
6,940 KB
testcase_08 AC 796 ms
26,348 KB
testcase_09 AC 708 ms
26,368 KB
testcase_10 AC 706 ms
26,412 KB
testcase_11 AC 708 ms
26,412 KB
testcase_12 AC 713 ms
26,284 KB
testcase_13 AC 321 ms
14,720 KB
testcase_14 AC 320 ms
12,988 KB
testcase_15 AC 293 ms
12,456 KB
testcase_16 AC 258 ms
18,444 KB
testcase_17 AC 490 ms
18,080 KB
testcase_18 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

/* #region Head */

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

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pll = pair<ll, ll>;
template <class T> using vc = vector<T>;
template <class T> using vvc = vc<vc<T>>;
using vll = vc<ll>;
using vvll = vvc<ll>;
using vld = vc<ld>;
using vvld = vvc<ld>;
using vs = vc<string>;
using vvs = vvc<string>;
template <class T, class U> using um = unordered_map<T, U>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqa = priority_queue<T, vc<T>, greater<T>>;
template <class T> using us = unordered_set<T>;

#define REP(i, m, n) for (ll i = (m), i##_len = (ll)(n); i < i##_len; ++(i))
#define REPM(i, m, n) for (ll i = (m), i##_max = (ll)(n); i <= i##_max; ++(i))
#define REPR(i, m, n) for (ll i = (m), i##_min = (ll)(n); i >= i##_min; --(i))
#define REPD(i, m, n, d) for (ll i = (m), i##_len = (ll)(n); i < i##_len; i += (d))
#define REPMD(i, m, n, d) for (ll i = (m), i##_max = (ll)(n); i <= i##_max; i += (d))
#define REPI(itr, ds) for (auto itr = ds.begin(); itr != ds.end(); itr++)
#define ALL(x) begin(x), end(x)
#define SIZE(x) ((ll)(x).size())
#define PERM(c)                                                                                                        \
    sort(ALL(c));                                                                                                      \
    for (bool c##p = 1; c##p; c##p = next_permutation(ALL(c)))
#define UNIQ(v) v.erase(unique(ALL(v)), v.end());
#define CEIL(a, b) (((a) + (b)-1) / (b))

#define endl '\n'
#define sqrt sqrtl
#define floor floorl
#define log2 log2l

constexpr ll INF = 1'010'000'000'000'000'017LL;
constexpr int IINF = 1'000'000'007LL;
constexpr ll MOD = 1'000'000'007LL; // 1e9 + 7
// constexpr ll MOD = 998244353;
constexpr ld EPS = 1e-12;
constexpr ld PI = 3.14159265358979323846;

template <typename T> istream &operator>>(istream &is, vc<T> &vec) { // vector 入力
    for (T &x : vec) is >> x;
    return is;
}
template <typename T> ostream &operator<<(ostream &os, vc<T> &vec) { // vector 出力 (for dump)
    os << "{";
    REP(i, 0, SIZE(vec)) os << vec[i] << (i == i_len - 1 ? "" : ", ");
    os << "}";
    return os;
}
template <typename T> ostream &operator>>(ostream &os, vc<T> &vec) { // vector 出力 (inline)
    REP(i, 0, SIZE(vec)) os << vec[i] << (i == i_len - 1 ? "\n" : " ");
    return os;
}

template <typename T, typename U> istream &operator>>(istream &is, pair<T, U> &pair_var) { // pair 入力
    is >> pair_var.first >> pair_var.second;
    return is;
}
template <typename T, typename U> ostream &operator<<(ostream &os, pair<T, U> &pair_var) { // pair 出力
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}

// map, um, set, us 出力
template <class T> ostream &out_iter(ostream &os, T &map_var) {
    os << "{";
    REPI(itr, map_var) {
        os << *itr;
        auto itrcp = itr;
        if (++itrcp != map_var.end()) os << ", ";
    }
    return os << "}";
}
template <typename T, typename U> ostream &operator<<(ostream &os, map<T, U> &map_var) { return out_iter(os, map_var); }
template <typename T, typename U> ostream &operator<<(ostream &os, um<T, U> &map_var) {
    os << "{";
    REPI(itr, map_var) {
        auto [key, value] = *itr;
        os << "(" << key << ", " << value << ")";
        auto itrcp = itr;
        if (++itrcp != map_var.end()) os << ", ";
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, set<T> &set_var) { return out_iter(os, set_var); }
template <typename T> ostream &operator<<(ostream &os, us<T> &set_var) { return out_iter(os, set_var); }
template <typename T> ostream &operator<<(ostream &os, pq<T> &pq_var) {
    pq<T> pq_cp(pq_var);
    os << "{";
    if (!pq_cp.empty()) {
        os << pq_cp.top(), pq_cp.pop();
        while (!pq_cp.empty()) os << ", " << pq_cp.top(), pq_cp.pop();
    }
    return os << "}";
}

void pprint() { cout << endl; }
template <class Head, class... Tail> void pprint(Head &&head, Tail &&... tail) {
    cout << head;
    if (sizeof...(Tail) > 0) cout << ' ';
    pprint(move(tail)...);
}

// dump
#define DUMPOUT cerr
void dump_func() { DUMPOUT << endl; }
template <class Head, class... Tail> void dump_func(Head &&head, Tail &&... tail) {
    DUMPOUT << head;
    if (sizeof...(Tail) > 0) DUMPOUT << ", ";
    dump_func(move(tail)...);
}

// chmax (更新「される」かもしれない値が前)
template <typename T, typename U, typename Comp = less<>> bool chmax(T &xmax, const U &x, Comp comp = {}) {
    if (comp(xmax, x)) {
        xmax = x;
        return true;
    }
    return false;
}

// chmin (更新「される」かもしれない値が前)
template <typename T, typename U, typename Comp = less<>> bool chmin(T &xmin, const U &x, Comp comp = {}) {
    if (comp(x, xmin)) {
        xmin = x;
        return true;
    }
    return false;
}

// ローカル用
#ifndef ONLINE_JUDGE
#define DEBUG_
#endif

#ifdef DEBUG_
#define DEB
#define dump(...)                                                                                                      \
    DUMPOUT << "  " << string(#__VA_ARGS__) << ": "                                                                    \
            << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]" << endl                                        \
            << "    ",                                                                                                 \
        dump_func(__VA_ARGS__)
#else
#define DEB if (false)
#define dump(...)
#endif

#define VAR(type, ...)                                                                                                 \
    type __VA_ARGS__;                                                                                                  \
    cin >> __VA_ARGS__;

template <typename T> istream &operator,(istream &is, T &rhs) { return is >> rhs; }
template <typename T> ostream &operator,(ostream &os, const T &rhs) { return os << ' ' << rhs; }

struct AtCoderInitialize {
    static constexpr int IOS_PREC = 15;
    static constexpr bool AUTOFLUSH = false;
    AtCoderInitialize() {
        ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
        cout << fixed << setprecision(IOS_PREC);
        if (AUTOFLUSH) cout << unitbuf;
    }
} ATCODER_INITIALIZE;

void Yn(bool p) { cout << (p ? "Yes" : "No") << endl; }
void YN(bool p) { cout << (p ? "YES" : "NO") << endl; }

/* #endregion */

// #include <atcoder/all>
// using namespace atcoder;

struct FullyIndexableDictionary {
    int len, blk;
    vector<unsigned> bit;
    vector<int> sum;

    FullyIndexableDictionary() {}
    FullyIndexableDictionary(int len) : len(len), blk((len + 31) >> 5), bit(blk, 0), sum(blk, 0) {}

    void set(int k) { bit[k >> 5] |= 1u << (k & 31); }

    void build() {
        sum[0] = 0;
        for (int i = 1; i < blk; i++) sum[i] = sum[i - 1] + __builtin_popcount(bit[i - 1]);
    }

    bool operator[](int k) const { return bool((bit[k >> 5] >> (k & 31)) & 1); }

    int rank(int k) { return sum[k >> 5] + __builtin_popcount(bit[k >> 5] & ((1u << (k & 31)) - 1)); }

    int rank(bool v, int k) { return (v ? rank(k) : k - rank(k)); }

    int select(bool v, int k) {
        if (k < 0 or rank(v, len) <= k) return -1;
        int l = 0, r = len;
        while (l + 1 < r) {
            int m = (l + r) >> 1;
            if (rank(v, m) >= k + 1)
                r = m;
            else
                l = m;
        }
        return r - 1;
    }

    int select(bool v, int i, int l) { return select(v, i + rank(v, l)); }
};

template <class T, int MAXLOG> struct WaveletMatrix {
    int len;
    FullyIndexableDictionary mat[MAXLOG];
    int zs[MAXLOG], buff1[MAXLOG], buff2[MAXLOG];
    static const T npos = -1;

    WaveletMatrix(vector<T> data) {
        len = data.size();
        vector<T> ls(len), rs(len);
        for (int dep = 0; dep < MAXLOG; dep++) {
            mat[dep] = FullyIndexableDictionary(len + 1);
            int p = 0, q = 0;
            for (int i = 0; i < len; i++) {
                bool k = (data[i] >> (MAXLOG - (dep + 1))) & 1;
                if (k)
                    rs[q++] = data[i], mat[dep].set(i);
                else
                    ls[p++] = data[i];
            }
            zs[dep] = p;
            mat[dep].build();
            swap(ls, data);
            for (int i = 0; i < q; i++) data[p + i] = rs[i];
        }
    }

    T access(int k) {
        T res = 0;
        for (int dep = 0; dep < MAXLOG; dep++) {
            bool bit = mat[dep][k];
            res = (res << 1) | bit;
            k = mat[dep].rank(bit, k) + zs[dep] * dep;
        }
        return res;
    }

    // return the number of v in [0,k)
    int rank(T v, int k) {
        int l = 0, r = k;
        for (int dep = 0; dep < MAXLOG; dep++) {
            buff1[dep] = l;
            buff2[dep] = r;
            bool bit = (v >> (MAXLOG - (dep + 1))) & 1;
            l = mat[dep].rank(bit, l) + zs[dep] * bit;
            r = mat[dep].rank(bit, r) + zs[dep] * bit;
        }
        return r - l;
    }

    // return the position of k-th v
    int select(T v, int k) {
        rank(v, len);
        for (int dep = MAXLOG - 1; dep >= 0; dep--) {
            bool bit = (v >> (MAXLOG - (dep + 1))) & 1;
            k = mat[dep].select(bit, k, buff1[dep]);
            if (k >= buff2[dep] or k < 0) return -1;
            k -= buff1[dep];
        }
        return k;
    }

    int select(T v, int k, int l) { return select(v, k + rank(v, l)); }

    // return k-th largest value in [l,r)
    T quantile(int l, int r, int k) {
        if (r - l <= k or k < 0) return -1;
        T res = 0;
        for (int dep = 0; dep < MAXLOG; dep++) {
            int p = mat[dep].rank(1, l);
            int q = mat[dep].rank(1, r);
            if (q - p > k) {
                l = p + zs[dep];
                r = q + zs[dep];
                res |= T(1) << (MAXLOG - (dep + 1));
            } else {
                k -= (q - p);
                l -= p;
                r -= q;
            }
        }
        return res;
    }

    T rquantile(int l, int r, int k) { return quantile(l, r, r - l - k - 1); }

    int freq_dfs(int d, int l, int r, T val, T a, T b) {
        if (l == r) return 0;
        if (d == MAXLOG) return (a <= val and val < b) ? r - l : 0;
        T nv = T(1) << (MAXLOG - d - 1) | val;
        T nnv = ((T(1) << (MAXLOG - d - 1)) - 1) | nv;
        if (nnv < a or b <= val) return 0;
        if (a <= val and nnv < b) return r - l;
        int lc = mat[d].rank(1, l), rc = mat[d].rank(1, r);
        return freq_dfs(d + 1, l - lc, r - rc, val, a, b) + freq_dfs(d + 1, lc + zs[d], rc + zs[d], nv, a, b);
    }

    // return number of points in [left, right) * [lower, upper)
    int rangefreq(int left, int right, T lower, T upper) { return freq_dfs(0, left, right, 0, lower, upper); }

    pair<int, int> ll(int l, int r, T v) {
        int res = 0;
        for (int dep = 0; dep < MAXLOG; dep++) {
            buff1[dep] = l;
            buff2[dep] = r;
            bool bit = (v >> (MAXLOG - (dep + 1))) & 1;
            if (bit) res += r - l + mat[dep].rank(bit, l) - mat[dep].rank(bit, r);
            l = mat[dep].rank(bit, l) + zs[dep] * bit;
            r = mat[dep].rank(bit, r) + zs[dep] * bit;
        }
        return make_pair(res, r - l);
    }

    int lt(int l, int r, T v) {
        auto p = ll(l, r, v);
        return p.first;
    }

    int le(int l, int r, T v) {
        auto p = ll(l, r, v);
        return p.first + p.second;
    }

    T succ(int l, int r, T v) {
        int k = le(l, r, v);
        return k == r - l ? npos : rquantile(l, r, k);
    }

    T pred(int l, int r, T v) {
        int k = lt(l, r, v);
        return k ? rquantile(l, r, k - 1) : npos;
    }
};

/* #region SegTree */

template <typename T> // T: 要素
struct SegmentTree {
    using F = function<T(T, T)>; // 要素と要素をマージする関数.max とか.

    ll n;  // 木のノード数
    ll nn; // 外から見た要素数
    F f; // 区間クエリで使う演算,結合法則を満たす演算.区間最大値のクエリを投げたいなら max 演算.
    T ti; // 値配列の初期値.演算 f に関する単位元.区間最大値なら単位元は 0. (a>0 なら max(a,0)=max(0,a)=a)
    vc<T> dat; // 1-indexed 値配列 (index は木の根から順に 1 | 2 3 | 4 5 6 7 | 8 9 10 11 12 13 14 15 | ...)

    // コンストラクタ.
    SegmentTree() {}
    // コンストラクタ.
    SegmentTree(F f, T ti) : f(f), ti(ti) {}

    // 指定要素数のセグメント木を初期化する
    void init(ll n_) {
        nn = n_;
        n = 1;
        while (n < n_) n <<= 1;
        dat.assign(n << 1, ti);
    }

    // ベクトルからセグメント木を構築する
    void build(const vc<T> &v) {
        ll n_ = v.size();
        init(n_);
        REP(i, 0, n_) dat[n + i] = v[i];
        REPR(i, n - 1, 1) dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
    }

    // インデックス k の要素の値を x にする.
    void set_val(ll k, T x) {
        dat[k += n] = x;
        while (k >>= 1) dat[k] = f(dat[(k << 1) | 0], dat[(k << 1) | 1]); // 上へ登って更新していく
    }

    // インデックス k の要素の値を取得する.
    T get_val(ll k) { return dat[k + n]; }

    // 半開区間 [a, b) に対するクエリを実行する
    T query(ll a, ll b) {
        if (a >= b) return ti;
        // assert(a<b)

        T vl = ti, vr = ti;
        for (ll l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
            if (l & 1) vl = f(vl, dat[l++]);
            if (r & 1) vr = f(dat[--r], vr);
        }
        return f(vl, vr);
    }

    // セグメント木上の二分探索
    template <typename C> int find(ll st, C &check, T &acc, ll k, ll l, ll r) {
        if (l + 1 == r) {
            acc = f(acc, dat[k]);
            return check(acc) ? k - n : -1;
        }
        ll m = (l + r) >> 1;
        if (m <= st) return find(st, check, acc, (k << 1) | 1, m, r);
        if (st <= l && !check(f(acc, dat[k]))) {
            acc = f(acc, dat[k]);
            return -1;
        }
        ll vl = find(st, check, acc, (k << 1) | 0, l, m);
        if (~vl) return vl;
        return find(st, check, acc, (k << 1) | 1, m, r);
    }

    // セグメント木上の二分探索.check(query(st, idx)) が真となる idx を返す.
    template <typename C> int find(ll st, C &check) {
        T acc = ti;
        return find(st, check, acc, 1, 0, n);
    }

    // セグメント木上の二分探索.
    // @param l 区間左端
    // @param check 条件
    // @return check(query(l,r)) が真となる最大の r(半開区間であることに注意).
    int max_right(int l, const function<bool(T)> &check) {
        assert(0 <= l && l <= nn);
        assert(check(ti));
        if (l == nn) return nn;
        l += n;
        T sm = ti;
        do {
            while (l % 2 == 0) l >>= 1;
            if (!check(f(sm, dat[l]))) {
                while (l < n) {
                    l = (2 * l);
                    if (check(f(sm, dat[l]))) {
                        sm = f(sm, dat[l]);
                        l++;
                    }
                }
                return l - n;
            }
            sm = f(sm, dat[l]);
            l++;
        } while ((l & -l) != l);
        return nn;
    }

    // セグメント木上の二分探索.
    // @param r 区間右端(半開区間であることに注意)
    // @param check 条件
    // @return check(query(l,r)) が真となる最小の l(半開区間であることに注意).
    int min_left(int r, const function<bool(T)> &check) {
        assert(0 <= r && r <= nn);
        assert(check(ti));
        if (r == 0) return 0;
        r += n;
        T sm = ti;
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!check(f(dat[r], sm))) {
                while (r < n) {
                    r = (2 * r + 1);
                    if (check(f(dat[r], sm))) {
                        sm = f(dat[r], sm);
                        r--;
                    }
                }
                return r + 1 - n;
            }
            sm = f(dat[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

    // セグ木の中身を標準出力する.
    void _dump() {
        REP(k, 0, nn) {
            T val = dat[k + n];
            cout << val << (k == nn - 1 ? '\n' : ' ');
        }
    }
};
/* #endregion */

// Problem
void solve() {
    VAR(ll, n, q);
    vll a(n);
    cin >> a;
    vll l(q), r(q);
    REP(i, 0, q) {
        cin >> l[i] >> r[i];
        --l[i]; //, --r[i];
    }

    ll mi = *min_element(ALL(a));
    REP(i, 0, n) a[i] -= mi;

    WaveletMatrix<ll, 60> wm(a);
    vll medians(q);
    REP(i, 0, q) {
        medians[i] = wm.rquantile(l[i], r[i], (r[i] - l[i] - 1) / 2);
        // dump(l[i], r[i], (r[i] - l[i] - 1) / 2, medians[i]);
    }
    // dump(medians);
    // exit(0);

    using pli = pair<ll, int>;
    vc<pli> values(n);
    REP(i, 0, n) values[i] = {a[i], i};
    sort(ALL(values));

    pqa<pair<int, int>> query;
    REP(i, 0, q) query.emplace(medians[i], i);
    vll small_sums(q);
    vll small_nums(q);

    auto f = [](int a, int b) { return a + b; };
    SegmentTree<int> seg(f, 0);
    seg.init(n);
    auto f2 = [](ll a, ll b) { return a + b; };
    SegmentTree<ll> seg2(f2, 0LL);
    seg2.init(n);

    REP(oi, 0, n) {
        int idx = values[oi].second; // 数列の idx 番目が使用される
        seg.set_val(idx, 1);
        seg2.set_val(idx, values[oi].first);
        // seg2._dump();

        while (!query.empty() && query.top().first == values[oi].first) {
            int qi = query.top().second;
            query.pop();
            small_nums[qi] = seg.query(l[qi], r[qi]);
            small_sums[qi] = seg2.query(l[qi], r[qi]);
            // dump(l[qi], r[qi], small_sums[qi]);
        }
    }
    // dump(small_sums, small_nums);

    REP(qi, 0, q) {
        ll num = r[qi] - l[qi];
        ll big_num = num - small_nums[qi];
        ll big_sum = seg2.query(l[qi], r[qi]) - small_sums[qi];
        ll median = medians[qi];
        // dump(num, big_num, small_nums[qi], big_sum, small_sums[qi], medians[qi]);
        ll sum = (big_sum - big_num * median) + (small_nums[qi] * median - small_sums[qi]);
        pprint(sum);
    }
}

// entry point
int main() {
    solve();
    return 0;
}
0