Cod sursa(job #2513292)

Utilizator Alex_BubBuburuzan Alexandru Alex_Bub Data 22 decembrie 2019 20:08:40
Problema Arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.31 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <cmath>

using namespace std;

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

const int NMax = 1e5, XMax = 1e6, BMax = 400;

int N, K, M, V[NMax + 5], A[NMax + 5], First[NMax + 5], Last[NMax + 5], id, Find[NMax + 5];
vector <int> G[NMax + 5];

struct
{
    int st, dr, l;
    bitset <XMax + 5> X;
}
B[BMax + 5];///bucket-urile pt Batog

void DFS(int Nod, int Tata)
{
    First[Nod] = ++K, V[K] = Nod;

    for(auto Vecin : G[Nod])
        if(Vecin != Tata)
            DFS(Vecin, Nod);

    Last[Nod] = K;
}

inline bool In(int x, int y)///daca x este in subarborele cu radacina y
{
    return (First[y] <= First[x] && Last[x] <= Last[y]);
}

void Update(int Nod, int val, int i)
{
    bool x = In(V[B[i].st], Nod), y = In(V[B[i].dr], Nod);

    if(x && y)
    {
        B[i].l += val;
        return;
    }

    for(int j = B[i].st; j <= B[i].dr; j++)
    {
        B[i].X[A[j]] = 0;

        if(In(V[j], Nod))
            A[j] += val;
    }

    for(int j = B[i].st; j <= B[i].dr; j++)
        B[i].X[A[j]] = 1;
}

int Querry(int s)
{
    for(int i = 1, val; i <= K; i++)
    {
        val = s - B[i].l;

        if(val < 0) continue;
        if(B[i].X[val] == 0) continue;

        for(int j = B[i].st; j <= B[i].dr; j++)
            if(A[j] == val)
                return j;
    }
    return -1;
}

int main()
{
    fin >> N >> M;

    for(int i = 1, a, b; i < N; i++)
    {
        fin >> a >> b;

        G[a].push_back(b);
        G[b].push_back(a);
    }
    DFS(1, 0);

    int lung = (int)sqrt(N) + 1; K = 0;

    for(int i = 1; i <= N; i += lung)
    {
        B[++K].st = i, B[K].dr = min(i + lung - 1, N);
        B[K].X[0] = 1;

        for(int j = B[K].st; j <= B[K].dr; j++)
            Find[V[j]] = K;
    }

    for(int i = 1, t, p, s; i <= M; i++)
    {
        fin >> t;

        if(t == 1)
        {
            fin >> p >> s;

            int st = Find[p], dr = Find[V[Last[p]]];///indicii bucket-urilor extreme

            for(int k = st; k <= dr; k++)
                Update(p, s, k);
        }
        else
        {
            fin >> s;
            fout << Querry(s) << '\n';
        }
    }
    fin.close();
    fout.close();

    return 0;
}