poj 3263 Tallest Cow 差分数列或线段树解区间修改

#include 
#include 
using namespace std;
const int max_n = 10024;
int c[max_n], d[max_n];
map, bool> existed;

int main() {
    int N, I, H, R;
    scanf("%d%d%d%d", &N, &I, &H, &R);
    for (int i = 0; i < R; ++i) {
        int a, b;
        scanf("%d%d", &a, &b);
        if (a > b) swap(a, b);
        if (existed[make_pair(a, b)]) continue;
        d[a + 1]--, d[b]++;
        existed[make_pair(a,b)] = 1;
    }
    for (int i = 1; i <= N; ++i) {
        c[i] = c[i - 1] + d[i];
        printf("%d\n", H + c[i]);
    }
    return 0;
}

线段树解法:

#include 
#include 

using namespace std;
const int max_n = 10024;
map, bool> existed;

int sum[max_n * 4], lazy[max_n * 4], L[max_n * 4], R[max_n * 4];

void build(int l, int r, int k) {
    sum[k] = 0, lazy[k] = 0, L[k] = l, R[k] = r;
    if (l == r)
        return;
    int m = (l + r) / 2;
    build(l, m, 2 * k);
    build(m + 1, r, 2 * k + 1);
}

void update(int k, int l, int r, int t) {

    if (L[k] == l && R[k] == r) {
        lazy[k] += t;
        return;
    }

    lazy[2 * k] += lazy[k];
    lazy[2 * k + 1] += lazy[k];
    sum[k] += (R[k] - L[k] + 1) * lazy[k] + (r - l + 1) * t;
    lazy[k] = 0;

    int m = (L[k] + R[k]) / 2;
    if (r <= m) {
        update(2 * k, l, r, t);
        return;
    }
    if (l >= m + 1) {
        update(2 * k + 1, l, r, t);
        return;
    }
    update(2 * k, l, m, t);
    update(2 * k + 1, m + 1, r, t);
}

int query(int k, int l, int r) {
    if (L[k] == l && R[k] == r) {
        return sum[k] + (r - l + 1) * lazy[k];
    }
    lazy[2 * k] += lazy[k];
    lazy[2 * k + 1] += lazy[k];
    sum[k] += (R[k] - L[k] + 1) * lazy[k];
    lazy[k] = 0;
    int m = (L[k] + R[k]) / 2;
    if (r <= m) {
        return query(2 * k, l, r);
    }
    if (l >= m + 1) {
        return query(2 * k + 1, l, r);
    }
    return query(2 * k, l, m) + query(2 * k + 1, m + 1, r);
}

int main() {
    int N, I, H, RR;
    scanf("%d%d%d%d", &N, &I, &H, &RR);
    build(1, N, 1);
    update(1, 1, N, H);
    query(1, 2, N);
    for (int i = 0; i < RR; ++i) {
        int a, b;
        scanf("%d%d", &a, &b);
        if (a > b) swap(a, b);
        if (existed[make_pair(a, b)]) continue;
        if (a + 1 <= b - 1) update(1, a + 1, b - 1, -1);
        existed[make_pair(a, b)] = 1;
    }

    for (int i = 1; i <= N; ++i) {
        printf("%d\n",query(1,i,i));
    }

    return 0;
}

 

你可能感兴趣的:(数据结构)