結果

問題 No.743 Segments on a Polygon
ユーザー finefine
提出日時 2018-10-06 01:40:19
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 72 ms / 2,000 ms
コード長 2,184 bytes
コンパイル時間 2,230 ms
コンパイル使用メモリ 172,160 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-26 18:11:52
合計ジャッジ時間 3,338 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
6,812 KB
testcase_01 AC 70 ms
6,816 KB
testcase_02 AC 70 ms
6,940 KB
testcase_03 AC 70 ms
6,944 KB
testcase_04 AC 69 ms
6,944 KB
testcase_05 AC 70 ms
6,940 KB
testcase_06 AC 71 ms
6,940 KB
testcase_07 AC 70 ms
6,940 KB
testcase_08 AC 72 ms
6,940 KB
testcase_09 AC 48 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

template <typename T>
struct SegmentTree {
    int n;
    vector<T> data;
    T INITIAL_VALUE;

    //使うときは、この2つを適宜変更する
    static T merge(T x, T y);
    void updateNode(int k, T x);

    SegmentTree(int size, T initial_value) {
        n = 1;
        INITIAL_VALUE = initial_value;
        while (n < size) n *= 2;
        data.resize(2 * n - 1, INITIAL_VALUE);
    }

    T getLeaf(int k) {
        return data[k + n - 1];
    }

    void update(int k, T x) {
        k += n - 1; //葉の節点
        updateNode(k, x);
        while (k > 0) {
            k = (k - 1) / 2;
            data[k] = merge(data[k * 2 + 1], data[k * 2 + 2]);
        }
    }

    //区間[a, b)に対するクエリに答える
    //k:節点番号, [l, r):節点に対応する区間
    T query(int a, int b, int k, int l, int r) {
        //[a, b)と[l, r)が交差しない場合
        if (r <= a || b <= l) return INITIAL_VALUE;
        //[a, b)が[l, r)を含む場合、節点の値
        if (a <= l && r <= b) return data[k];
        else {
            //二つの子をマージ
            T vl = query(a, b, k * 2 + 1, l, (l + r) / 2);
            T vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
            return merge(vl, vr);
        }
    }

    //外から呼ぶ用
    T query(int a, int b) {
        return query(a, b, 0, 0, n);
    }
};

//使うときは以下2つを変更
template <typename T>
T SegmentTree<T>::merge(T x, T y) {
    return x + y;
}

template <typename T>
void SegmentTree<T>::updateNode(int k, T x) {
    data[k] += x;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    ll ans = 0;
    SegmentTree<int> st(m, 0);
    vector<int> a(n), b(n), ids(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
        if (a[i] > b[i]) swap(a[i], b[i]);
        ids[i] = i;
    }
    sort(ids.begin(), ids.end(), [&](const int i1, const int i2){return a[i1] < a[i2];});
    for (int i : ids) {
        ans += st.query(a[i], b[i]);
        st.update(b[i], 1);
    }
    cout << ans << endl;
    return 0;
}
0