Cod sursa(job #1631985)

Utilizator TimitocArdelean Andrei Timotei Timitoc Data 5 martie 2016 20:42:17
Problema Arbore Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.1 kb
#include <iostream>
#include <cstdio>
#include <vector>
#define MAXN 100050

using namespace std;

vector<int> graf[MAXN];
int parent[MAXN], n, m;
int val[MAXN];

void citire()
{
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n-1; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
        graf[x].push_back(y);
        graf[y].push_back(x);
	}
}

void dfs(int nod = 1)
{
	for (const auto& y : graf[nod])
        if (!parent[y])
			parent[y] = nod, dfs(y);
}

void update(int x, int sum)
{
	val[x] += sum;
}

int get(int sum, int nod = 1, int crt = 0)
{
    crt += val[nod];
    if (crt == sum)
		return nod;
    for (const auto& y : graf[nod])
		if (y != parent[nod]) {
			int x = get(sum, y, crt);
			if (x != -1) return x;
		}
	return -1;
}

int main()
{
	freopen("arbore.in", "r", stdin);
	freopen("arbore.out", "w", stdout);

    citire();
    parent[1] = 1;
	dfs();
	for (int i = 1; i <= m; i++) {
		int tip, x, y;
        scanf("%d ", &tip);
        if (tip == 1) {
			scanf("%d %d", &x, &y);
            update(x, y);
        }
        else {
			scanf("%d", &x);
            printf("%d\n", get(x));
        }
	}

    return 0;
}