Cod sursa(job #1185013)

Utilizator misinozzz zzz misino Data 14 mai 2014 20:08:08
Problema Arbore Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.16 kb
#include<fstream>
#include<vector>
#include<bitset>
#include<cmath>

#define S 1000100
#define N 100100

using namespace std;

ifstream f("arbore.in");
ofstream g("arbore.out");

int n,m,i,op,p,y,x,s,lg,nrb,k,st[N],dr[N],e[N],val[N],sumab[N];

vector<int>v[N];

bitset<S> ok[400];

inline int banda(int x){
    if(x % lg == 0)
        return x / lg;

    return x / lg + 1;
}

inline int pozi(int x){
    return x * lg - lg + 1;
}

inline int pozf(int x){
    return x * lg;
}

inline void dfs(int x){
    st[x] = ++ k;
    e[k] = x;

    for(vector<int>::iterator it = v[x].begin() ; it != v[x].end() ; ++ it)
    if(!st[*it])
    {
        dfs(*it);
    }

    dr[x] = k;
}

inline void update2(int band,int a,int b,int s){

    int i,pf,li,ls;

    li = max(a , pozi(band));
    ls = min(b , pozf(band));

    for(i = pozi(band) , pf = pozf(band) ; i <= pf ; ++ i)
        ok[band][val[i]] = 0;

    for(i = li ; i <= ls ; ++ i)
        val[i] += s;

    for(i = pozi(band) , pf = pozf(band) ; i <= pf ; ++ i)
        ok[band][val[i]] = 1;
}

inline void update(int a , int b , int s){
    for(int i = banda(a) ; i <= banda(b) ; ++ i)
    {
        if(a <= pozi(i) && pozf(i) <=b)
            sumab[i] += s;
        else
            update2(i , a , b , s);
    }
}

inline int query(int s){
    int i, j ,pf;
    for(i = 1 ; i <= nrb ; ++ i)
    if(sumab[i] <= s && ok[i][s - sumab[i]])
    {
        for(j = pozi(i) ,pf = pozf(i) ; j <= pf  && j <= n; ++ j)
            if(val[j] == s - sumab[i])
            return e[j];
    }
}

int main()
{
    f >> n >> m;

    lg = sqrt(n);

    for(i = 1 ; i < n ; ++ i)
    {
        f >> x >> y;

        v[x].push_back(y);
        v[y].push_back(x);
    }

    dfs(1);

    nrb = banda(n);

    for(i = 1 ; i <= nrb ; ++ i)
    {
        ok[i][0] = 1;
    }

    for(i = 1 ; i <= m ; ++ i)
    {
        f >> op ;

        if(op == 1)
        {
            f >> p >> s;

            update(st[p] , dr[p] , s);
        }
        else
        {
            f >> s;

            g << query(s) << '\n';
        }
    }

    return 0;
}