Cod sursa(job #3232098)

Utilizator iusty64Iustin Epanu iusty64 Data 28 mai 2024 21:07:37
Problema Arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.38 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <math.h>
#include <unordered_map>

using namespace std;
const int sqrtMax = 317;
const int Vmax = 100001;
int n, m, sqrtN;

vector<int> L[Vmax];
int v[Vmax], poz[Vmax], contor[Vmax], node[Vmax];
bool viz[Vmax];
int cnt = 0, cntBuc = 0;
int st[317], dr[317], sumBuc[317];
unordered_map<int, int> fr[Vmax];

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

void update(int nod, int val){
  int left = poz[nod];
	int right = poz[nod] + contor[nod];
	int bucLeft = (left / sqrtN) + 1;
	if(left % sqrtN == 0)
		bucLeft--;
	int bucRight = (right / sqrtN) + 1;
	if(right % sqrtN == 0)
		bucRight--;
	if(left == right){
		v[left] += val;
		fr[bucLeft][v[left]]++;
		fr[bucLeft][v[left] - val]--;
		if(fr[bucLeft][v[left] - val] == 0)
        fr[bucLeft].erase(fr[bucLeft].find(v[left] - val));
		return;
	}
	for(int i = left; i <= dr[bucLeft]; i++){
		v[i] += val;
		fr[bucLeft][v[i]]++;
		fr[bucLeft][v[i] - val]--;
		if(fr[bucLeft][v[i] - val] == 0)
        fr[bucLeft].erase(fr[bucLeft].find(v[i] - val));
	}
	for(int i = bucLeft + 1; i < bucRight; i++){
		sumBuc[i] += val;
	}
	for(int i = st[bucRight]; i <= right; i++){
		v[i] += val;
		fr[bucRight][v[i]]++;
		fr[bucRight][v[i] - val]--;
		if(fr[bucRight][v[i] - val] == 0)
        fr[bucRight].erase(fr[bucRight].find(v[i] - val));
	}
}

void query(int val){
	int ok = 0;
	for(int buc = 1; buc <= sqrtN; buc++){
		if(fr[buc][val - sumBuc[buc]]){
			for(int i = st[buc]; i <= dr[buc]; i++){
				if(v[i] == val - sumBuc[buc]){
					fout << node[i] << '\n';
					ok = 1;
					break;
				}
			}
		}
	}
	if(!ok)
		fout << -1 << '\n';
}

void dfs(int nod){
	cnt++;
	if(cnt % sqrtN == 0){
		cntBuc++;
		st[cntBuc] = cnt - sqrtN + 1;
		dr[cntBuc] = cnt;
	}
	else if(cnt == n){
		cntBuc++;
		st[cntBuc] = dr[cntBuc - 1] + 1;
		dr[cntBuc] = cnt;
	}
	poz[nod] = cnt;
	node[cnt] = nod;
	viz[nod] = true;
	for(int son : L[nod]){
		if(!viz[son]){
			dfs(son);
			contor[nod] += 1 + contor[son];
		}
	}
}

int main(){
	fin >> n >> m;
	sqrtN = sqrt(n);
	for(int i = 1; i < n; i++){
		int x, y;
		fin >> x >> y;
		L[x].push_back(y);
	}
	dfs(1);
	for(int i = 1; i <= m; i++){
		int c, x, y;
		fin >> c;
		if(c == 1){
			fin >> x >> y;
			update(x, y);
		}
		else{
			fin >> x;
			query(x);
		}
	}
	return 0;
}