Cod sursa(job #843249)

Utilizator stoicatheoFlirk Navok stoicatheo Data 27 decembrie 2012 17:02:38
Problema Arbore Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.15 kb
#include <cstdio>
#include <vector>
#define MAXN 100001
#define ARBSIZE 262145
#define maxim(a,b) (a>b?a:b)
using std::vector;
 
int n, m, euler[MAXN], ep, start[MAXN], end[MAXN], x, y;
char color[MAXN];
bool found;
 
int max[ARBSIZE], inc[ARBSIZE];
 
vector<int> G[MAXN];
 
void dfs(int node)
{
    euler[++ep] = node;
    start[node] = ep;
     
    color[node] = 1;
    int len = G[node].size();
    for (int i = 0 ; i < len ; ++i)
        if (color[G[node][i]] == 0)
            dfs(G[node][i]);
     
    end[node] = ep;
}
 
void update(int node, int left, int right)
{
    if (start[x] <= left && right <= end[x])
        inc[node] += y;
    else
    {
        int mid = (left + right) >> 1;
        if (start[x] <= mid)
            update(node << 1, left, mid);
        if (end[x] > mid)
            update((node << 1) + 1, mid + 1, right);
    }
     
    if (left == right)
        max[node] = inc[node];
    else
        max[node] = maxim(max[node << 1], max[(node << 1) + 1]) + inc[node];
}
 
void query(int node, int left, int right)
{
    x -= inc[node];
     
    if (x == 0)
    {
        found = true;
        printf("%d\n", euler[left]);
    }
    else if (left != right && x > 0 && max[node] - inc[node] >= x)
    {
        int mid = (left + right) >> 1;
        query(node << 1, left, mid);
        if (!found)
            query((node << 1) + 1, mid + 1, right);
    }
     
    x += inc[node];
}
 
int main()
{
    freopen("arbore.in", "r", stdin);
    freopen("arbore.out","w",stdout);
     
    scanf("%d %d", &n, &m);
     
    for (int i = 1 ; i < n ; ++i)
    {
        int a, b;scanf("%d %d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
     
    dfs(1);
     
    for (int i = 1 ; i <= m ; ++i)
    {
        int command; scanf("%d %d", &command, &x);
        if (command == 1)
        {
            scanf("%d", &y);
            update(1, 1, n);
        }
        else
        {
            found = false;
            query(1, 1, n);
             
            if (!found)
                printf("%d\n", -1);
        }
    }
     
    return 0;
}