module queue
    implicit none
    private
    integer:: last
    integer, allocatable:: q(:)
    public:: q_init, q_push, q_pop, q_is_exist
contains
subroutine q_init(n)
    integer:: n
    allocate(q(n))
    last = 0
end subroutine

subroutine q_push(x)
    integer:: x
    last = last + 1
    q(last) = x
end subroutine

function q_pop() result(ret)
    integer:: ret
    ret = q(last)
    last = last - 1
end function

function q_is_exist() result(ret)
    logical:: ret
    if(last > 0)then
        ret = .true.
    else
        ret = .false.
    end if
end function
end module

program main
    use queue
    integer:: n,q,k
    integer,allocatable:: a(:), b(:), x(:), y(:)
    integer(8), allocatable:: c(:)
    integer:: i,j, seek
    logical, allocatable:: is_seeked(:)
    ! import --- ---
    read*, n
    allocate(a(n-1), b(n-1), c(n-1), is_seeked(n))
    call q_init(n)
    do i = 1, n-1
        read*, a(i), b(i), c(i)
    end do

    read*, q, k
    allocate(x(q), y(q))

    do i = 1, q
        read*, x(i), y(i)
    end do
    ! --- ---

    call q_push(k)

    do while(q_is_exist())
        seek = q_pop()
        do i = 1, n
            if(a(i)/=seek .and. b(i)/=seek) cycle
            if(seek == b(i))                call swap(a(i),b(i))
            if(is_seeked(b(i)))             cycle
            call q_push(b(i))
        end do
        is_seeked(seek) = .true.
    end do

contains
    subroutine swap(xx,yy)
        integer, intent(inout):: xx,yy
        integer:: t
        t=xx; x=yy; yy=t
    end subroutine
end program