Cod sursa(job #1495684)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 3 octombrie 2015 13:42:05
Problema Arbore Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.5 kb
#include <fstream>
#include <vector>
#include <array>
#include <bitset>
#include <cmath>
using namespace std;

constexpr int maxv = 1000000;

constexpr int chunk_sz = 512;
constexpr int get_chunk(const int p){
	return p>>9; }

constexpr int get_poz_in_chunk(const int p){
	return p & (chunk_sz-1); }

constexpr int get_first_chunk_ind(const int ch){
	return ch<<9; }

class the_structure{
	int n, n_chunks;
	vector<bitset<maxv+1>> apare_in_chunk;
	vector<int> delta, elemente;
	void redo_chunk(const int ch){
		apare_in_chunk[ch] = 0;
		for(int i = get_first_chunk_ind(ch), lst = get_first_chunk_ind(ch+1); i < lst; ++i){
			apare_in_chunk[ch].set(delta[ch] + elemente[i]); } }
public:
	the_structure(const int sz): n(sz), n_chunks(get_chunk(n-1)+1), apare_in_chunk(n_chunks, 1), delta(n_chunks, 0), elemente(n){}
	void update(const int st, const int dr, const int val){
		const int ch_st = get_chunk(st), ch_dr = get_chunk(dr);
		if(ch_st == ch_dr){
			for(int i = st; i <= dr; ++i){
				elemente[i] += val; }
			redo_chunk(ch_st); }
		else{
			for(int i = st, lst = get_first_chunk_ind(ch_st+1); i < lst; ++i){
				elemente[i] += val; }
			redo_chunk(ch_st);
			for(int i = ch_st+1; i < ch_dr; ++i){
				delta[i] += val; }
			for(int i = get_first_chunk_ind(ch_dr); i <= dr; ++i){
				elemente[i] += val; }
			redo_chunk(ch_dr); } }
	int query(const int val){
		for(int i = 0; i < n_chunks; ++i){
			if(apare_in_chunk[i][val - delta[i]]){
				for(int j = get_first_chunk_ind(i); ; ++j){
					if(elemente[j] + delta[i] == val){
						return j; } } } }
		return -1; } };

void rename(const vector<vector<int> >& arb, const int cur, const int prev, vector<int>& poz,
	vector<int>& last_child, vector<int>& inv_poz, int& ind_cur){
	poz[cur] = ind_cur;
	inv_poz[ind_cur] = cur;
	++ind_cur;
	for(const auto next : arb[cur]){
		if(next != prev){
			rename(arb, next, cur, poz, last_child, inv_poz, ind_cur); } }
	last_child[cur] = ind_cur-1; }

int main(){
	ifstream f("arbore.in");
	ofstream g("arbore.out");
	int n, m;
	f >> n >> m;
	vector<vector<int> > arb(n);
	for(int i = 0, a, b; i < n-1; ++i){
		f >> a >> b;
		--a, --b;
		arb[a].push_back(b);
		arb[b].push_back(a); }
	vector<int> poz(n), last_child(n), inv_poz(n);
	int ind_cur = 0;
	rename(arb, 0, -1, poz, last_child, inv_poz, ind_cur);
	the_structure ts(n);
	for(int i = 0, t, p, s; i < m; ++i){
		f >> t;
		if(t == 1){
			f >> p >> s;
			--p;
			ts.update(poz[p], last_child[p], s); }
		else{
			f >> s;
			const auto rez = ts.query(s);
			g << (rez == -1 ? -1 : inv_poz[rez]+1) << '\n'; } }
	return 0; }