The Quest for the Sacred Groves

시간 제한1초메모리 제한2048 MB

요약
주어진 트리에서 순열의 연속 부분 구간이 유도하는 부분 그래프가 연결되도록 하는 구간의 개수를 센다.
난이도

어려움10점 중 8점

유형
트리, 분할 정복, 세그먼트 트리, DFS
정답자
아직 제출이 없습니다

문제

In the heart of ancient Romania, where dense forests meet towering mountains, there lies the enchanted kingdom of Vatra Codrilor. The kingdom is protected by nn sacred groves, numbered from 11 to nn, each watched over by a guardian spirit. These groves are connected by secret paths known only to the wise elders, forming a vast and ancient tree of life. The paths are pure and free of any treacherous loops, ensuring that a traveler can always find their way through the kingdom without getting lost. Formally, the secret paths form a tree.

One night, as the full moon rises, the nn guardians receive a divine message from the Dacian gods. The message is an ancient scroll with a sacred list called pp. Formally, pp is a sequence of length nn where every number from 11 to nn appears exactly once. This list tells the guardians the order in which they must stand in the final battle to protect the forest.

However, the wise guardians know that there's more to this list. For each subsegment \[ℓ,r]\[\ell, r] of the list, if the groves p_ℓ,p_ℓ+1,…,p_rp\_{\ell}, p\_{\ell+1}, \ldots, p\_{r} are all connected through the secret paths without involving any other groves, the guardians from these groves can meet together and harness the power of the forest's magic.

Your challenge is to help the guardians discover how many such subsegments exist in the sacred list pp. Can you count the magical segments in the dance of the guardians, ensuring the power of the groves remains strong and united?

입력

The first line contains an integer nn (1≤n≤2⋅1051 \leq n \leq 2 \cdot 10^5).

Each of the next n−1n - 1 lines contains two integers, u_iu\_i and v_iv\_i (1≤u_i,v_i≤n1 \leq u\_i, v\_i \leq n), denoting an edge of the tree.

The last line contains the nn distinct integers p_1,p_2,…,p_np\_1, p\_2, \ldots, p\_n (1≤p_i≤n1 \leq p\_i \leq n).

출력

You need to write a single line with an integer: the number of subsegments \[ℓ,r]\[\ell, r] such that 1≤ℓ≤r≤n1 \leq \ell \leq r \leq n and the groves p_ℓ,p_ℓ+1,…,p_rp\_{\ell}, p\_{\ell+1}, \ldots, p\_{r} form a connected undirected graph.

예제2

  1. 예제 1

    입력
    7
    1 2
    1 3
    3 4
    3 5
    3 6
    2 7
    7 3 4 1 2 5 6
    
    예상 출력
    16
    
  2. 예제 2

    입력
    7
    1 2
    1 3
    3 4
    3 5
    3 6
    2 7
    7 2 4 1 3 5 6
    
    예상 출력
    22