Mai intai trebuie sa te autentifici.

Cod sursa(job #3190846)

Utilizator YosifIosif Andrei Stefan Yosif Data 8 ianuarie 2024 09:58:17
Problema Arbore Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <bits/stdc++.h>
using namespace std;

string file = "arbore";
ifstream fin(file + ".in");
ofstream fout(file + ".out");

int n, m;
vector<int> g[100001];
int sz, first[100001], last[100001], a[300001];
unordered_map<int, int> M[600];
int add[600], v[300001];
const int block = 100000;

void dfs(int node = 1, int p = -1) {

    a[++sz] = node;
    first[node] = last[node] = sz;

    for (auto &i: g[node])
        if (i != p) {

            dfs(i, node);
            a[++sz] = node;
            last[node] = sz;
        }
}

int main() {

    fin >> n >> m;

    for (int i = 1; i < n; i++) {

        int x, y;
        fin >> x >> y;

        g[x].push_back(y);
        g[y].push_back(x);
    }

    dfs();

    for (int i = 1; i <= sz; i++)
        M[i / block][0]++;

    for (int i = 1; i <= m; i++) {

        int type;
        fin >> type;

        if (type == 1) {

            int p, s;
            fin >> p >> s;

            if (last[p] - first[p] + 1 <= 2 * block) {

                for (int j = first[p]; j <= last[p]; j++) {

                    M[j / block][v[j]]--;
                    v[j] += s;
                    M[j / block][v[j]]++;
                }
            }
            else {

                int x, y;
                x = first[p];
                y = last[p];

                if (x != 1 && x % block != 0)
                    x = (x / block + 1) * block;

                for (int j = first[p]; j < x; j++) {

                    M[j / block][v[j]]--;
                    v[j] += s;
                    M[j / block][v[j]]++;
                }

                if (y % block != block - 1)
                    y -= y % block - 1;

                for (int j = last[p]; j > y; j--) {

                    M[j / block][v[j]]--;
                    v[j] += s;
                    M[j / block][v[j]]++;
                }

                for (int j = x; j <= y; j += block)
                    add[j / block] += s;
            }
        }
        else {

            int s;
            fin >> s;

            int aux = 0;

            for (int j = 1; j <= sz; j = (j / block + 1) * block) {

                if (M[j / block][s - add[j / block]]) {

                    aux = j;
                    break;
                }
            }

            if (aux == 0) {

                fout << "-1\n";
                continue;
            }

            for (int j = aux; j < (aux / block + 1) * block; j++)
                if (v[j] + add[j / block] == s) {

                    fout << a[j] << '\n';
                    break;
                }
        }
    }

    return 0;
}