Cod sursa(job #1393521)

Utilizator addy01adrian dumitrache addy01 Data 19 martie 2015 15:24:30
Problema Arbore Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.12 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int MAXN = 100000 + 10;

vector <int> Graf[MAXN];

int N, M;
int now;
int H[2 * MAXN];
int First[MAXN], Last[MAXN];
bool Viz[MAXN];
int Sum[MAXN * 8], Max[MAXN * 8];

void DFS (int nod)
{
    now ++;
    H[now] = nod;
    First[nod] = now;
    Viz[nod] = 1;

    vector <int> :: iterator it;
    for (it = Graf[nod].begin (); it != Graf[nod].end (); ++ it)
        if (!Viz[*it]){
            DFS (*it);
            ++ now;
            H[now] = nod;
        }

    Last[nod] = now;
}

inline int _max (const int &A, const int &B)
{
    if (A > B)
        return A;

    return B;
}

void update (int nod, int st, int dr, int x, int val)
{
    if (First[x] <= st && dr <= Last[x]){
        Sum[nod] += val;
        Max[nod] = Sum[nod] + _max (Max[2 * nod], Max[2 * nod + 1]);

        return;
    }

    int mid = (st + dr) / 2;

    if (First[x] <= mid)
        update (nod * 2, st, mid, x, val);
    if (mid < Last[x])
        update (nod * 2 + 1, mid + 1, dr, x, val);

    Max[nod] = Sum[nod] + _max (Max[2 * nod], Max[2 * nod + 1]);
}

int found;

void query (int nod, int st, int dr, int val)
{
    if (found > 0)
        return;

    if (Sum[nod] == val){
        found = H[st];
        return;
    }

    if (st < dr && Sum[nod] < val && Max[nod] >= val){
        int mid = (st + dr) / 2;
        query (nod * 2, st, mid, val - Sum[nod]);
        query (nod * 2 + 1, mid + 1, dr, val - Sum[nod]);
    }
}

int main()
{
    int i, a, b;
    int op;

    in >> N >> M;
    for (i = 1; i < N; i ++){
        in >> a >> b;
        Graf[a].push_back (b);
        Graf[b].push_back (a);
    }

    DFS (1);

    for (i = 1; i <= M; i ++){
        in >> op;

        if (op == 1){
            in >> a >> b;
            update (1, 1, now, a, b);
        }
        else{
            in >> a;
            found = -1;
            query (1, 1, now, a);
            out << found << "\n";
        }
    }

    return 0;
}