Cod sursa(job #3232092)

Utilizator iusty64Iustin Epanu iusty64 Data 28 mai 2024 20:42:54
Problema Arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.41 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];
unordered_map<int, int> valFr[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]--;
		valFr[bucLeft][v[left]] = node[left];
		return;
	}
	for(int i = left; i <= dr[bucLeft]; i++){
		v[i] += val;
		fr[bucLeft][v[i]]++;
		fr[bucLeft][v[i] - val]--;
		valFr[bucLeft][v[i]] = node[i];
		//cout << left << " " << right << " " << i << " " << valFr[bucLeft][v[i]] << '\n';
	}
	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]--;
		valFr[bucRight][v[i]] = node[i];
		//cout << left << " " << right << " " << i << " " << valFr[bucRight][v[i]] << '\n';
	}
}

void query(int val){
	int ok = 0;
	for(int buc = 1; buc <= sqrtN; buc++){
		if(fr[buc][val - sumBuc[buc]]){
			//cout << fr[buc][val - sumBuc[buc]] << " " << val - sumBuc[buc] << '\n';
			fout << valFr[buc][val - sumBuc[buc]] << '\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;
}