[bzoj5334][loj2573][TJOI2018]数学计算【线段树】

【题目链接】
  https://loj.ac/problem/2573
【题解】
  线段树维护区间乘积。
  时间复杂度O(NlogN)
【代码】

# include <bits/stdc++.h>
# define    ll      long long
# define    inf     0x3f3f3f3f
# define    N       100010
using namespace std;
int read(){
    int tmp = 0, fh = 1; char ch = getchar();
    while (ch < '0' || ch > '9') {if (ch == '-') fh = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9'){tmp = tmp * 10 + ch - '0'; ch = getchar(); }
    return tmp * fh;
}
struct Tree{
    int sum, pl, pr;
}T[N * 3];
int P, place, n, rt;
void build(int &p, int l, int r){
    p = ++place;
    T[p].pl = T[p].pr = 0;
    T[p].sum = 1;
    if (l != r){
        int mid = (l + r) / 2;
        build(T[p].pl, l, mid);
        build(T[p].pr, mid + 1, r);
    }
}
void inc(int p, int l, int r, int x, int num){
    if (l == r){
        T[p].sum = num;
        return;
    }
    int mid = (l + r) / 2;
    if (mid >= x) inc(T[p].pl, l, mid, x, num);
        else inc(T[p].pr, mid + 1, r, x, num);
    T[p].sum = 1ll * T[T[p].pl].sum * T[T[p].pr].sum % P;
}
void dec(int p, int l, int r, int x){
    if (l == r){
        T[p].sum = 1;
        return;
    }
    int mid = (l + r) / 2;
    if (mid >= x) dec(T[p].pl, l, mid, x);
        else dec(T[p].pr, mid + 1, r, x);
    T[p].sum = 1ll * T[T[p].pl].sum * T[T[p].pr].sum % P;
}
int main(){
    for (int opt = read(); opt--;){
        n = read(), P = read();
        place = 0;
        build(rt, 1, n);
        for (int i = 1; i <= n; i++){
            int op = read(), num = read();
            if (op == 1){
                inc(rt, 1, n, i, num);
                printf("%d\n", T[rt].sum);
            }
            else {
                dec(rt, 1, n, num);
                printf("%d\n", T[rt].sum);
            }
        }
    }
    return 0;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页