Cod sursa(job #1590815)

Utilizator alexandra_udristoiuUdristoiu Alexandra Maria alexandra_udristoiu Data 5 februarie 2016 16:20:09
Problema Arbore Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.43 kb
#include<fstream>
#include<cmath>
#include<bitset>
#include<vector>
#define f first
#define s second
using namespace std;
int n, m, i, j, s, p, st, dr, x, y, nr, rad, t, ii;
int v[100005], ff[100005], ad[100005], aux[100005], viz[100005];
pair<int, int> w[100005];
bitset<1000002> d[320];
vector<int> vec[100005];
ifstream fin("arbore.in");
ofstream fout("arbore.out");
void dfs(int nod){
    nr++;
    w[nod].f = nr;
    aux[nr] = nod;
    viz[nod] = 1;
    for(int i = 0; i < vec[nod].size(); i++){
        if(viz[vec[nod][i]] == 0){
            dfs(vec[nod][i]);
        }
    }
    w[nod].s = nr;
}
void solve(int x, int p, int u){
    int i;
    int st = (x - 1) * rad + 1, dr = x * rad;
    for(i = st; i <= dr; i++){
        d[x][ v[i] ] = 0;
    }
    for(i = st; i <= dr; i++){
        v[i] += ad[x];
        if(i >= p && i <= u){
            v[i] += s;
        }
        d[x][ v[i] ] = 1;
    }
    ad[x] = 0;
}
int main(){
    fin>> n >> m;
    for(i = 1; i < n; i++){
        fin>> x >> y;
        vec[x].push_back(y);
        vec[y].push_back(x);
    }
    dfs(1);
    nr = 0;
    rad = sqrt(n * 1.0);
    for(i = 1; i <= n; i++){
        if(i % rad == 1){
            nr++;
            d[nr][0] = 1;
        }
        ff[i] = nr;
    }
    for(i = 1; i <= m; i++){
        fin>> t;
        if(t == 1){
            fin>> p >> s;
            x = w[p].f;
            y = w[p].s;
            if(ff[x] == ff[y]){
                solve(ff[x], x, y);
            }
            else{
                solve(ff[x], x, ff[x] * rad);
                solve(ff[y], (ff[y] - 1) * rad + 1, y);
                for(j = ff[x] + 1; j < ff[y]; j++){
                    ad[j] += s;
                }
            }
        }
        else{
            fin>> s;
            for(j = 1; j <= nr; j++){
                if(s - ad[j] < 0){
                    continue;
                }
                if(d[j][s - ad[j]] == 1){
                    st = (j - 1) * rad + 1;
                    dr = j * rad;
                    for(ii = st; ii <= dr; ii++){
                        if(v[ii] + ad[j] == s){
                            fout<< aux[ii] <<"\n";
                            break;
                        }
                    }
                    break;
                }
            }
            if(j == nr + 1){
                fout<<"-1\n";
            }
        }
    }
    return 0;
}