原文
Ashish has a tree consisting of nodes numbered to rooted at node . The -th node in the tree has a cost , and binary digit is written in it. He wants to have binary digit written in the -th node in the end.
To achieve this, he can perform the following operation any number of times:
- Select any nodes from the subtree of any node , and shuffle the digits in these nodes as he wishes, incurring a cost of . Here, he can choose ranging from to the size of the subtree of .
He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.
Help him find the minimum total cost he needs to spend so that after all the operations, every node has digit written in it, or determine that it is impossible.
Input
First line contains a single integer denoting the number of nodes in the tree.
-th line of the next lines contains 3 space-separated integers , , — the cost of the -th node, its initial digit and its goal digit.
Each of the next n−1 lines contain two integers , , meaning that there is an edge between nodes and in the tree.
Output
Print the minimum total cost to make every node reach its target digit, and −1 if it is impossible.
Examples
input
1 | 5 |
output
1 | 4 |
input
1 | 5 |
output
1 | 24000 |
input
1 | 2 |
output
1 | -1 |
Note
The tree corresponding to samples and are:
In sample , we can choose node and for a cost of and select nodes , shuffle their digits and get the desired digits in every node.
In sample , we can choose node and for a cost of , select nodes and exchange their digits, and similarly, choose node and for a cost of , select nodes and exchange their digits to get the desired digits in every node.
In sample , it is impossible to get the desired digits, because there is no node with digit initially.
题意
有一颗树,树根为节点1,每个节点有三个属性,代表当前节点的状态,代表当前节点需要变成的状态,代表修改节点状态所需要的花费。
现在能够进行一种操作:
选择一颗以为根节点的子树,任意的修改其子树中的个节点的状态(互相交换),这个操作的花费为。
现在需要求解使树中所有节点都能变成目标状态所需要的最小开销,如果不存在则进行判定。
思路
首先可以知道,如果一个节点的父亲节点为,且有,那么所有以节点为根的子树上涉及到的操作都可以移动到其父节点上进行,可以对整棵树进行的操作而不改变本身的结果。
完成以上操作之后,根节点到叶子结点的值实际上就是一个单调递减的序列,可以从叶子结点往根节点进行遍历,一旦当前子树上存在可以操作的成对节点就进行操作。
时间复杂度为遍历树的时间复杂度。
代码
1 |
|