Cod sursa(job #1343806)

Utilizator ooptNemes Alin oopt Data 15 februarie 2015 22:23:55
Problema Arbore Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.02 kb
/// arbore
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

#define NMax 100005
#define pb push_back

using namespace std;

ifstream f("arbore.in");
ofstream g("arbore.out");

int n, q;
vector<int> V[NMax];
int poz;
int ord[2 * NMax];
int st[NMax];
int dr[NMax];
int arb_sum[8 * NMax];
int arb_max[8 * NMax];
int sol;

void read() {
    f>>n>>q;
    for (int i=1;i<n;i++) {
        int a, b;
        f>>a>>b;
        V[a].pb(b);
        V[b].pb(a);
    }
}

void dfs(int nod, int tata) {
    ord[++poz] = nod;
    st[nod] = poz;
    int l = V[nod].size();
    for (int i = 0; i < l; i++)
        if (V[nod][i] != tata) dfs(V[nod][i], nod);
    ord[++poz] = nod;
    dr[nod] = poz;
}

void update(int nod, int left, int right, int x, int val) {
    if (st[x] <= left && right <= dr[x]) {
        arb_sum[nod] += val;
        arb_max[nod] = arb_sum[nod] + max(arb_max[2 * nod], arb_max[2 * nod + 1]);
        return;
    }
    int m = (left + right) / 2;
    if (st[x] <= m) update(2 * nod, left, m, x, val);
    if (dr[x] > m) update(2 * nod + 1, m + 1, right, x, val);
    arb_max[nod] = arb_sum[nod] + max(arb_max[2 * nod], arb_max[2 * nod + 1]);
}

void query(int nod, int left, int right, int suma) {
    if (sol > 0) return;
    if (arb_sum[nod] == suma) {
        sol = ord[left];
        return;
    }
    if (left < right && arb_sum[nod] < suma && arb_max[nod] >= suma) {
        int m = (left + right) / 2;
        query(2 * nod, left, m, suma - arb_sum[nod]);
        query(2 * nod + 1, m + 1, right, suma - arb_sum[nod]);
    }
}
int main() {

    read();
    dfs(1, 0);
    for (int i=1;i<=q;i++) {
        int type; f>>type;
        if (type == 1) {
            int p, s;
            f>>p>>s;
            update(1,1,poz,p,s);
        } else if (type == 2) {
            int s;
            f>>s;
            sol = -1;
            query(1,1,poz,s);
            g<<sol<<'\n';
        }
    }

    f.close(); g.close();
    return 0;
}