Cod sursa(job #2127653)

Utilizator cipri321Marin Ciprian cipri321 Data 10 februarie 2018 21:18:31
Problema Arbore Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb
#include <fstream>
#include <bitset>
#include <vector>
#include <iostream>
#define DIM 100001
#define DG 335
using namespace std;
ifstream fi("arbore.in");
ofstream fo("arbore.out");
int n,m;
int A[DIM],G[DG];
bitset<1000001> E[DG];
int st[DIM],sf[DIM],U[DIM];
vector<int> V[DIM];
int VIZ[DIM],ind;
int tip,p,s;
void dfs(int nod)
{
	VIZ[nod]=1;
	st[nod]=++ind;
	U[ind]=nod;
	for(auto to:V[nod])
		if(!VIZ[to])
			dfs(to);
	sf[nod]=ind;
}
int gru(int ind)
{
	int rez=ind/DG+1;
	if(ind%DG==0)
		rez--;
	return rez;
}
void update(int st,int dr,int val)
{
	int g=gru(st);
	for(int i=(g-1)*DG+1;i<=g*DG;i++)
		E[g][A[i]]=0;
	for(int i=st;i<=dr&&i<=g*DG;i++)
		A[i]+=val;
	for(int i=(g-1)*DG+1;i<=g*DG;i++)
		E[g][A[i]]=1;
	if(g==gru(dr))
		return;
	g++;
	while(g<gru(dr))
		G[g]+=val,g++;
	for(int i=(g-1)*DG+1;i<=g*DG;i++)
		E[g][A[i]]=0;
	for(int i=(g-1)*DG+1;i<=dr;i++)
		A[i]+=val;
	for(int i=(g-1)*DG+1;i<=g*DG;i++)
		E[g][A[i]]=1;
}
void query(int val)
{
	for(int g=1;g<gru(n);g++)
		if(val>=G[g]&&E[g][val-G[g]])
		{
			for(int i=(g-1)*DG+1;i<=g*DG;i++)
				if(A[i]==val-G[g])
				{
					fo<<U[i]<<"\n";
					return;
				}
		}
	for(int i=(gru(n)-1)*DG+1;i<=n;i++)
		if(A[i]==val-G[gru(n)])
		{
			fo<<U[i]<<"\n";
			return;
		}
	fo<<-1<<"\n";
}
int main()
{
	fi>>n>>m;
	for(int i=1;i<n;i++)
	{
		int a,b;
		fi>>a>>b;
		V[a].push_back(b);
		V[b].push_back(a);
	}
	dfs(1);
	for(int i=1;i<=m;i++)
	{
		fi>>tip;
		if(tip==1)
		{
			fi>>p>>s;
			update(st[p],sf[p],s);
		}
		else
		{
			fi>>s;
			query(s);
		}
	}
	fi.close();
	fo.close();
	return 0;
}