#P3365. 改造二叉树

改造二叉树

Description

In computer science, a binary tree is an ordered tree in which each node has at most two children. The children are usually called the “left child” and the “right child.” Binary trees are used as binary search trees and binary heaps. Then he discussed binary search trees with others. What is a binary search tree? A binary search tree is first a binary tree. Let keypkey_p denote the value stored at node pp. For each node pp, if it has a left child lchlch, then keyp>keylchkey_p > key_{lch}; if it has a right child rchrch, then keyp<keyrchkey_p < key_{rch}. Note that in this problem, the binary search tree must satisfy: for every node, all keys in its left subtree are less than the node’s key, and all keys in its right subtree are greater than the node’s key.

But thoughtful Xiao L is not satisfied with only learning the basics. He considered this problem: given a binary tree, you can arbitrarily change the values of nodes. Changing the value of a node counts as one modification, and that node cannot be modified again. You want to transform it into a binary search tree, and at any time the value of every node must be an integer (it can be negative or 00). What is the minimum number of modifications required?

This surely won’t stump you! If you help Xiao L solve this problem, maybe he will give you 116\dfrac{1}{16} of his final assets.

Input Format

The first line contains a positive integer nn, the number of nodes in the binary tree.

The second line contains nn positive integers separated by spaces. The ii-th number aia_i is the original value of node ii.

Then follow n1n - 1 lines, each containing two non-negative integers fafa and chch. The (i+2)(i + 2)-th line describes the parent index fafa of node i+1i + 1 and the parent-child relation chch (ch=0ch = 0 means i+1i + 1 is the left child, ch=1ch = 1 means i+1i + 1 is the right child).

To make it a bit easier for you, Xiao L guarantees that node 11 is the root of the binary tree.

Output Format

Output a single line containing one integer, the minimum number of modifications.

3
2 2 2
1 0
1 1
2

Hint

Constraints

  • For 20%20\% of the testdata: n10n \leq 10, ai100a_i \leq 100.
  • For 40%40\% of the testdata: n100n \leq 100, ai200a_i \leq 200.
  • For 60%60\% of the testdata: n2000n \leq 2000.
  • For 100%100\% of the testdata: n105n \leq 10^5, ai<231a_i < 2^{31}.

Translated by ChatGPT 5