• ACM-ICPC 2018 沈阳赛区网络预赛 J Ka Chang


    Ka Chang

    思路:

    dfs序+树状数组+分块

    先dfs处理好每个节点的时间戳

    对于每一层,如果这一层的节点数小于sqrt(n),那么直接按照时间戳在树状数组上更新

    如果这一层节点个数大于sqrt(n),那么直接存一下这一层每个节点的大小(都是一样的),这样的层数不会超过sqrt(n)层

    然后查询的时候先在树状数组查询答案,然后再遍历第二种层数,加到答案中

    复杂度:n*sqrt(n)*log(n)

    代码:

    #pragma GCC optimize(2)
    #pragma GCC optimize(3)
    #pragma GCC optimize(4)
    #include<bits/stdc++.h>
    using namespace std;
    #define fi first
    #define se second
    #define pi acos(-1.0)
    #define LL long long
    #define mp make_pair
    #define pb push_back
    #define ls rt<<1, l, m
    #define rs rt<<1|1, m+1, r
    #define ULL unsigned LL
    #define pll pair<LL, LL>
    #define pii pair<int, int>
    #define piii pair<pii, int>
    #define mem(a, b) memset(a, b, sizeof(a))
    #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    #define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
    //head
    
    const int N = 1e5 + 10;
    vector<int>g[N];
    int in[N], out[N], deep[N], n, tot = 0;
    LL val[N], bit[N];
    vector<int>dfn[N];
    vector<int>big;
    void add(int x, int v) {
        while(x <= n) bit[x] += v, x += x&-x;
    }
    LL query(int x) {
        LL ans = 0;
        while(x) ans += bit[x], x -= x&-x;
        return ans;
    }
    void dfs(int o, int u, int d) {
        deep[u] = d;
        in[u] = ++tot;
        dfn[d].pb(tot);
        for (int v:g[u]) {
            if(v != o) dfs(u, v, d+1); 
        }
        out[u] = tot;
    }
    int main() {
        int q, u, v, blo, ty, l, x;
        scanf("%d %d", &n, &q);
        blo = sqrt(n);
        for (int i = 1; i < n; i++) {
            scanf("%d %d", &u, &v);
            g[u].pb(v);
            g[v].pb(u);
        }
        dfs(1, 1, 0);
        for(int i = 0; i < n; i++) {
            if(dfn[i].size() > blo) big.pb(i);
        }
        while(q--) {
            scanf("%d", &ty);
            if(ty == 1) {
                scanf("%d %d", &l, &x);
                if(dfn[l].size() <= blo) {
                    for (int i = 0; i < dfn[l].size(); i++) {
                        add(dfn[l][i], x);
                    }
                }
                else val[l] += x;
            }
            else {
                scanf("%d", &x);
                LL ans = query(out[x]) - query(in[x]-1);
                for (int i = 0; i < big.size(); i++) {
                    int d = big[i];
                    int t = upper_bound(dfn[d].begin(), dfn[d].end(), out[x]) - lower_bound(dfn[d].begin(), dfn[d].end(), in[x]);
                    ans += 1LL * t * val[d];
                }
                printf("%lld
    ", ans);
            }
        }
        return 0;
    }
  • 相关阅读:
    SCOI2012 奇怪的游戏
    AHOI2013 差异
    HAOI2018 染色
    HNOI2015 开店
    PKUWC2018 随机游走
    HAOI2015 按位或
    Luogu4859 二项式反演
    CTSC2018 混合果汁
    yii2.0邮件发送问题解决
    yii2.0 elasticsearch模糊查询
  • 原文地址:https://www.cnblogs.com/widsom/p/9615439.html
Copyright © 2020-2023  润新知