Cod sursa(job #796235)

Utilizator danalex97Dan H Alexandru danalex97 Data 10 octombrie 2012 21:11:45
Problema Arbore Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.85 kb
#include <cstdio>
#include <bitset>
#include <vector>

#define NMax 100005
#define SqrtMax 320
#define SMax 1000005
#define BuffMax 10000000

using namespace std;

vector <int> G[NMax];
int N, V[NMax], Tree[NMax], TreeL[NMax], TreeR[NMax], BuffI;
int NList, ListV[SqrtMax], ListL[SqrtMax], ListR[SqrtMax];
bitset <SMax> H[SqrtMax];
bitset <NMax> Visited;
char Buffer[BuffMax];

inline void BuildLists ()
{
    for (NList=1; NList*NList<=N; ++NList); --NList;
    int ListI=0;
    for (int i=1; i<=N; ++ListI)
    {
        H[ListI][0]=1;
        ListL[ListI]=i;
        ListR[ListI]=i+NList-1;
        i+=NList;
    }
    NList=ListI;
    ListR[NList-1]=N;
}

inline void Update (int &UL, int &UR, int &UV)
{
    for (int i=0; i<NList; ++i)
    {
        if (UR<ListL[i] or UL>ListR[i])
        {
            continue;
        }
        if (UL<=ListL[i] and ListR[i]<=UR)
        {
            ListV[i]+=UV;
            continue;
        }
        for (int j=ListL[i]; j<=ListR[i]; ++j)
        {
            H[i][V[j]]=0;
            V[j]+=(ListV[i]+UV*(UL<=j and j<=UR));
        }
        ListV[i]=0;
        for (int j=ListL[i]; j<=ListR[i]; ++j)
        {
            H[i][V[j]]=1;
        }
    }
}

inline int Query (int &Q)
{
    for (int i=0; i<NList; ++i)
    {
        if (Q<ListV[i])
        {
            continue;
        }
        if (H[i][Q-ListV[i]])
        {
            Q-=ListV[i];
            for (int j=ListL[i]; j<=ListR[i]; ++j)
            {
                if (V[j]==Q)
                {
                    return Tree[j];
                }
            }
        }
    }
    return -1;
}

inline void DFS (int X)
{
    Visited[X]=1;
    Tree[++Tree[0]]=X;
    TreeL[X]=Tree[0];
    for (vector <int> :: iterator V=G[X].begin (); V!=G[X].end (); ++V)
    {
        if (!Visited[*V])
        {
            DFS (*V);
        }
    }
    TreeR[X]=Tree[0];
}

inline int ReadX()
{
    int X=0;
    while(!(Buffer[BuffI]>='0' && Buffer[BuffI]<='9'))
    {
        ++BuffI;
    }
    while(Buffer[BuffI]>='0' && Buffer[BuffI]<='9')
    {
        X=X*10+Buffer[BuffI]-'0';
        ++BuffI;
    }
    return X;
}

int main()
{
    freopen ("arbore.in", "r", stdin);
    freopen ("arbore.out", "w", stdout);
    fread (Buffer, 1, BuffMax, stdin);
    int M;
    N=ReadX (); M=ReadX ();
    for (int i=2; i<=N; ++i)
    {
        int X, Y;
        X=ReadX (); Y=ReadX ();
        G[X].push_back (Y);
        G[Y].push_back (X);
    }
    DFS (1);
    BuildLists ();
    for (; M>0; --M)
    {
        int Type, X, Y;
        Type=ReadX (); X=ReadX ();
        if (Type==1)
        {
            Y=ReadX ();
            Update (TreeL[X], TreeR[X], Y);
        }
        else
        {
            printf ("%d\n", Query (X));
        }
    }
    return 0;
}