#include <iostream>
#include<stdlib.h>

struct list_t
{
    int data;
    struct list_t*next;
};

struct list_t*add(struct list_t*l,int data)
{
    struct list_t*new_item=(struct list_t*)malloc(sizeof(struct list_t));
    new_item->next=0;
    new_item=data;
    if(l==0)return new_item;
    struct list_t*temp=l;
    while(temp->next)temp=temp->next;
    temp->next=new_item;
    return l;
};

struct list_t*rem(struct list_t*l)
{
    struct list_t*new_item=(struct list_t*)malloc(sizeof(struct list_t));
    if(!l)return 0;
    struct list_t*temp=l;
    while(temp->next)temp=temp->next;
    new_item=temp->next;
    temp->next=0;
    free(new_item);
    return l;
};

int main()
{
    /*int n;
    int res=0;
    std::cin>>n;
    int *x=(int*)malloc(n*sizeof(int)),*y=(int*)malloc(n*sizeof(int));
    for(int i=0;i<n;i++)
    {
        std::cin>>x[i]>>y[i];
    }*/
    int n=8;
    int res=0;
    int x[]={0,1,2,3,4,5,6,1},y[]={1,5,4,2,3,0,6,0};
    struct list_t **balls=(list_t**)malloc((n+1)*sizeof(struct list_t));
    int *weight=(int*)malloc(sizeof(int)*(n+1));
    balls[0]=add(balls[0],0);
    weight[0]=0;
    for(int i=1;i<=n;i++)
    {
        if(y[i-1]==0)
        {
            balls[i]=rem(balls[x[i-1]]);
            struct list_t *temp=balls[i];
            while(temp)
            {
                //std::cout<<temp->data<<"\n";
                weight[i]+=temp->data;
                temp=temp->next;
            }
        }
        else
        {
            balls[i]=add(balls[x[i-1]],y[i-1]);
            struct list_t*t=balls[x[i-1]];
            weight[i]=weight[x[i-1]]+y[i-1];
        }
        res+=weight[i];
    }
    std::cout<<res;
    return 0;
}
