P26429 [AtCoder] Three Safes
提高
题目描述

Problem Description

AtCoder's office has a tree structure consisting of $ N $ rooms connected by $ N - 1 $ corridors. Corridor $ i $ connects room $ V_i $ and room $ i + 1 $ bidirectionally.

You have installed safes in 3 different rooms out of the $ N $ rooms in the office. For each room $ v $, you calculated the median distance $ M_v $ from room $ v $ to each of the rooms where a safe is installed. However, you have forgotten which rooms the safes were installed in.

Given the structure of the office and the values $ M_v $ for each room $ v $, find the number of different sets of 3 rooms that could be the locations where the safes were installed.

The distance between room $ x $ and room $ y $ is defined as the minimum number of corridors you need to pass through to move from room $ x $ to room $ y $.

Input Format

The input is given from the standard input in the following format:

$ N $ $ V_1 $ $ V_2 $ $\vdots$ $ V_{N - 1} $ $ M_1 $ $ M_2 $ $\vdots$ $ M_N $

Output Format

Output the answer.

Sample Input and Output

Sample Input #1

8
1
2
1
4
1
6
4
2
1
2
1
2
3
4
2

Sample Output #1

2

Sample Input #2

5
1
2
3
4
1
1
1
1
1

Sample Output #2

0

Notes/Hints

Constraints

  • $3 \leq N \leq 100,000$
  • $1 \leq V_i \leq i$ ($1 \leq i \leq N - 1$)
  • $1 \leq M_v \leq N - 1$ ($1 \leq v \leq N$)
  • All input values are integers.

Sample Explanation 1

The sets of rooms that satisfy the conditions are (room $ 1 $, room $ 3 $, room $ 5 $) and (room $ 1 $, room $ 3 $, room $ 8 $), totaling 2 sets.

输入格式

见题面 Input 部分

输出格式

见题面 Output 部分

样例输入
8 1 2 1 4 1 6 4 2 1 2 1 2 3 4 2
样例输出
2