Cod sursa(job #1343789)

Utilizator ooptNemes Alin oopt Data 15 februarie 2015 22:04:58
Problema Arbore Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.01 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 node, int father) {
    ord[++poz] = node;
    st[node] = poz;

    for (unsigned i=0;i<V[node].size();i++)
        if (V[node][i] != father)
            dfs(V[node][i], node);

    ord[++poz] = node;
    dr[node] = poz;
}

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

    int mid = (left+right)/2;
    if (mid >= st[p]) update(2*nod, left, mid, p, s);
    if (mid < dr[p]) update(2*nod+1, mid+1, right, p, s);
    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 = 0;
            query(1,1,poz,s);
            g<<sol<<'\n';
        }
    }

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