#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 denote the value stored at node . For each node , if it has a left child , then ; if it has a right child , then . 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 ). 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 of his final assets.
Input Format
The first line contains a positive integer , the number of nodes in the binary tree.
The second line contains positive integers separated by spaces. The -th number is the original value of node .
Then follow lines, each containing two non-negative integers and . The -th line describes the parent index of node and the parent-child relation ( means is the left child, means is the right child).
To make it a bit easier for you, Xiao L guarantees that node 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 of the testdata: , .
- For of the testdata: , .
- For of the testdata: .
- For of the testdata: , .
Translated by ChatGPT 5
京公网安备 11011102002149号