Cod sursa(job #1857543)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 26 ianuarie 2017 12:53:36
Problema Arbore Scor 100
Compilator cpp Status done
Runda Lista lui wefgef Marime 2.6 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <cmath>

using namespace std;

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

typedef vector< int > graf;

const int nmax = 1e5;
const int radmax = 320;
const int valmax = 1e6;

bitset<valmax + 1> b[radmax + 1];

int n, rad, nrb;
bool viz[nmax + 1];
int v[nmax + 1], ord[nmax + 1], first[nmax + 1], last[nmax + 1];
int ct[nmax + 1];

int u[nmax + 1];
pair<int, int> intv[radmax + 1];

graf g[nmax + 1];

void dfs (int nod) {
    viz[ nod ] = 1;
    ord[ ++ rad ] = nod;
    first[ nod ] = rad;

    for (const auto &i : g[ nod ]) {
        if (viz[ i ] == 0) {
            dfs( i );
        }
    }

    last[ nod ] = rad;
}

void precalc() {
    rad = sqrt( n );

    for (int i = 1; i <= n; i += rad) {
        intv[ ++ nrb ].first = i;
        intv[ nrb ].second = i + rad - 1;

        b[ nrb ][ 0 ] = 1;
    }
    intv[ nrb ].second = n;

    for (int i = 1; i <= n; ++ i) {
        u[ i ] = (i - 1) / rad + 1;
    }
}

void recalc (int ind) {
    for (int i = intv[ ind ].first; i <= intv[ ind ].second; ++ i) {
        b[ ind ][ v[ i ] ] = 1;
    }
}

void update (int x, int y, int val) {
    int bx = u[ x ], by = u[ y ];

    for (int i = bx + 1; i <= by - 1; ++ i) {
        ct[ i ] += val;
    }

    if (u[ x ] == u[ y ]) {
        for (int i = x; i <= y; ++ i) {
            b[ bx ][ v[ i ] ] = 0;
            v[ i ] += val;
        }
        recalc( bx );
    } else {
        for (int i = x; i <= intv[ bx ].second; ++ i) {
            b[ bx ][ v[ i ] ] = 0;
            v[ i ] += val;
        }
        for (int i = intv[ by ].first; i <= y; ++ i) {
            b[ by ][ v[ i ] ] = 0;
            v[ i ] += val;
        }
        recalc( bx ); recalc( by );
    }
}

int query (int val) {
    int unde = 0;
    for (int i = 1; i <= nrb; ++ i) {
        if (val - ct[ i ] >= 0 && b[ i ][val - ct[ i ]] == 1) {
            unde = i; break;
        }
    }

    if (unde == 0) return -1;

    for (int i = intv[ unde ].first; i <= intv[ unde ].second; ++ i) {
        if (v[ i ] == val - ct[ unde ]) {
            return ord[ i ];
        }
    }
    return -2;
}

int main() {
    int q;
    fin >> n >> q;
    for (int i = 1; i < n; ++ i) {
        int x, y;
        fin >> x >> y;
        g[ x ].push_back( y );
        g[ y ].push_back( x );
    }

    dfs( 1 );
    precalc();

    while (q --) {
        int tip, x, y;
        fin >> tip >> x;

        if (tip == 1) {
            fin >> y;
            update(first[ x ], last[ x ], y);
        } else {
            fout << query( x ) << "\n";
        }
    }

    fin.close();
    fout.close();
    return 0;
}