Blue vertex distance sums on a tree
Time limit5sMemory limit512 MB
Process paint and distance-sum queries on a weighted tree, reporting for each query 2 the total distance from x to all blue vertices.
- Level
Hard8 of 10
- Topics
- Tree, Prefix sum, DFS, Dynamic programming
- Solved
- No attempts yet
Problem
There is a tree with vertices, numbered through . Every edge has a length. The distance between two vertices is the sum of the edge lengths on the unique path that joins them.
At the start every vertex is white. Process the following two kinds of queries in the given order.
- Query 1: paint vertex blue. If vertex is already blue it stays blue, and it is still counted once.
- Query 2: compute the sum of the distances between vertex and every blue vertex. If vertex is itself blue, the distance is part of the sum. If no vertex is blue, the sum is .
Write a program that answers every query 2.
Input
The first line has the number of vertices () and the number of queries ().
Each of the next lines has an edge as , , : vertices and are joined by an edge of length . (, , )
Each of the next lines has one query. The first integer is the kind of the query, or , and the second integer is ().
Output
For each query 2, print its answer on its own line, in the order the queries are given.