Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Codeforces 369E:Valera and Queries 題解與樹狀數組做法

編輯:關於 Android 程式設計

E. Valera and Queries 時間限制每組測資 2 秒 記憶體限制每組測資 512 MB 輸入標準輸入 輸出標準輸出

Valera 非常喜歡線段,這次要處理的問題如下:在 Ox 座標軸上有 n 條線段,第 i 條線段的起點為 li、終點為 ri(記為 [li, ri])。接著有 m 筆查詢,每筆查詢給定一個數字 cnti 以及一組位於座標軸上的點。對於每筆查詢,答案等於「至少包含查詢中一個點」的線段數量。若線段 [l, r] 滿足 l ≤ q ≤ r,就代表它包含點 q。

輸入格式

第一行兩個整數 n、m(1 ≤ n, m ≤ 3·105),代表線段數量與查詢數量。接下來 n 行描述線段,每行兩個正整數 li、ri(1 ≤ li ≤ ri ≤ 106)。之後 m 行描述查詢,每行開頭是 cnti,接著是嚴格遞增的 cnti 個相異正整數座標。所有查詢的點總數不超過 3·105。

輸出格式

輸出 m 個非負整數,第 i 個即第 i 筆查詢的答案。

範例

輸入:
3 3
1 3
4 5
6 7
3 1 4 7
2 4 5
1 8

輸出:
3
1
0

這題的核心思路是「反過來看」:不去枚舉每條線段包含哪些點,而是把每筆查詢的相鄰點切成若干個區間,統計有多少條線段完全落在某個區間之外,再用總線段數減掉,就是答案。這是相當典型的樹狀數組(Binary Indexed Tree)應用題。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 3000010;
int ans[maxn];
struct Interval {
    int l, r, id;
} I[maxn], q[maxn];
bool cmp(Interval a, Interval b) {
    return a.r < b.r;
}
int tree[maxn];
int lowbit(int x) { return x & -x; }
void Add(int x) {
    while (x < 1000010) {
        tree[x] += 1;
        x += lowbit(x);
    }
}
int getSum(int x) {
    int sum = 0;
    while (x > 0) {
        sum += tree[x];
        x -= lowbit(x);
    }
    return sum;
}
int main() {
    int n, m;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        scanf("%d%d", &I[i].l, &I[i].r);
        I[i].id = i;
    }
    int e = 0;
    for (int i = 0; i < m; i++) {
        int t;
        scanf("%d", &t);
        for (int j = 0; j < t; j++) {
            scanf("%d", &q[e].r);
            q[e].id = i;
            if (j == 0) q[e].l = 0;
            else q[e].l = q[e-1].r;
            e++;
        }
        q[e].id = i;
        q[e].l = q[e-1].r;
        q[e++].r = 1000010;
    }
    sort(I, I + n, cmp);
    sort(q, q + e, cmp);
    for (int i = 0; i < m; i++) ans[i] = n;
    memset(tree, 0, sizeof(tree));
    int j = 0;
    for (int i = 0; i < e; i++) {
        while (j < n && I[j].r < q[i].r) {
            Add(I[j].l);
            j++;
        }
        ans[q[i].id] -= getSum(q[i].r - 1) - getSum(q[i].l);
    }
    for (int i = 0; i < m; i++) printf("%d\n", ans[i]);
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved