Cod sursă (job #465917)

Utilizator avatar Constantin. Constantin Dragancea Constantin. IP ascuns
Problemă Rafaela (lot liceu) Compilator cpp | 2.02 kb
Rundă Arhiva de probleme Status evaluat
Dată 3 apr. 2019 19:51:12 Scor 0
#include <bits/stdc++.h>
using namespace std;
typedef pair <int,int> pii;

#define N 200010
#define fi first
#define se second
int n, a[N], q, sz[N], pnod[N], mxc[N], chain[N], nrl = 1, cnt[N], ord[N], k, fw[N], bgn[N];
vector <int> v[N];

void update(int pos, int val){
    for (; pos <= n; pos += (pos & -pos)) fw[pos] += val;
}

int get(int pos){
    int rs = 0;
    for (; pos; pos -= (pos & -pos)) rs += fw[pos];
    return rs;
}

int query(int x, int y){
    return (get(y) - get(x - 1));
}

int getsz(int q, int pr){
    sz[q] = 1;
    int mx = 0, idx;
    for (auto it: v[q]){
        if (it == pr) continue;
        pnod[it] = q;
        int tt = getsz(it, q);
        if (tt > mx) mx = tt, idx = it;
        sz[q] += tt;
    }
    if (mx) mxc[q] = idx;
    return sz[q];
}

void hld(int q, int pr){
    ++k;
    chain[q] = nrl;
    ord[q] = ++cnt[nrl];
    if (ord[q] == 1) bgn[nrl] = k;
    update(k, a[q]);
    if (mxc[q]) hld(mxc[q], q);
    for (auto it: v[q]){
        if (it == pr || it == mxc[q]) continue;
        nrl++; hld(it, q);
    }
}

int ask(int id){
    int aux = 0, stotal = get(n), mx = 0;
    for (auto it: v[id]){
        if (it == pnod[id]) continue;
        int st = bgn[chain[it]] + ord[it] - 1;
        int tt = query(st, st + sz[it]-1);
        if (tt > mx) mx = tt;
        aux += tt;
    }
    if (stotal-aux > mx) mx = stotal - aux;
    return mx;
}

int main(){
    ifstream cin ("rafaela.in");
    ofstream cout ("rafaela.out");
    cin >> n >> q;
    for (int i=1, x, y; i<n; i++){
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for (int i=1; i<=n; i++) cin >> a[i];
    getsz(1, -1);
    hld(1, -1);
    for (int i=1, nr, id; i<=q; i++){
        char c;
        cin >> c;
        if (c == 'U'){
            cin >> nr >> id;
            update(bgn[chain[id]] + ord[id] -1, nr);
        }
        else{
            cin >> id;
            cout << ask(id) << '\n';
        }
    }
    return 0;
}