Cod sursa(job #621949)

Utilizator dacyanMujdar Dacian dacyan Data 16 octombrie 2011 22:43:03
Problema Arbore Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.35 kb
#include <fstream>
#include <bitset>
#include <vector>
#define DIM 100001
#define DIM_S 1000001
#define DIM_RAD 400
using namespace std;

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

int n, q, pas, rad;
vector<int> G[DIM];
int in[DIM], out[DIM], mart[DIM];
int c[DIM], a[DIM];
bitset<DIM_S> p[DIM_RAD];

void Read();
void DF(int nod);
void Update2(int grup, int st, int dr, int s);
void Update(int st, int dr, int s);
int Query(int s);

int main()
{
	Read();
	DF(1);
	for (rad = 1; rad * rad < n; ++rad);
	if (rad * rad != n) rad--;

	int nod, s, k;
	while (q--)
	{
		fin >> k;
		if (k == 1) 
		{
			fin >> nod >> s;
			Update(in[nod], out[nod], s);
		}
		else
		{
			fin >> s;
			fout << Query(s) << '\n';
		}
	}
	
	fin.close();
	fout.close();
	return 0;
}

void Read()
{
	fin >> n >> q;
	int x, y;
	for (int i = 1; i < n; ++i)
	{
		fin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
}

void DF(int nod)
{
	if (in[nod]) return;
	in[nod] = ++pas;
	mart[pas] = nod;
	for (int i = 0; i < G[nod].size(); ++i)
	{
		int son = G[nod][i];
		if (in[son]) continue;
		DF(son);
	}
	out[nod] = pas;
}

void Update(int st, int dr, int s)
{
	int rad1, rad2;
	if (st <= rad * rad)
	{
		rad1 = st / rad;
		if (st % rad) rad1++;
	}
	else rad1 = rad + 1;
	
	if (dr <= rad * rad)
	{
		rad2 = dr / rad;
		if (dr % rad) rad2++;
	}
	else rad2 = rad + 1;

	if (rad1 != rad2)
	{
		Update2(rad1, st, rad1 * rad, s);
		if (rad2 != rad + 1) Update2(rad2, (rad1-1)*rad, dr, s);
			else Update2(rad + 1, rad * rad + 1, dr, s);
		for (int i = rad1 + 1; i < rad2; ++i)
			c[i] += s;
		return;
	}
	Update2(rad1, st, dr, s);
	
}

void Update2(int grup, int st, int dr, int s)
{
	
	for (int i = st; i <= dr; ++i)
	{
		p[grup][a[i]] = 0;
		a[i] += s;
		 
	}
	if (grup != rad + 1)
	{
		for (int i = (grup-1) * rad + 1; i < rad * grup + 1 && i <= n; ++i)
			p[grup][a[i]] = 1;
	}
	else
	{
		for (int i = rad * rad + 1; i <= n; ++i)
			p[grup][a[i]] = 1;
	}
}

int Query(int s)
{
	for (int i = 1; i <= rad; ++i)
		if (c[i] <= s && p[i][s - c[i]])
			for (int j = (i-1) * rad + 1; j < rad * i + 1; ++j)
				if (a[j] == s - c[i]) return mart[j];
	if (c[rad+1] <= s && p[rad+1][s-c[rad+1]])
		for (int i = rad * rad + 1; i <= n; ++i)
			if (a[i] == s - c[i]) return mart[i];
	return -1;
}