Absolute tree

4.3

6 votes
Segment tree, Euler Tour and Path, Algorithms, Depth-first search, Graphs
Problem

You are given a tree of size N. The tree isrooted at 1 and each node i (1iN) contains a value Ai.

You are also given an array K of size N. For each node i (1iN), you are required to determine the distance to the closest node j in the subtree of i such that AiAj∣≥Ki.

Note

  • Distance between two nodes is calculated as the shortest path between them and it is represented as the number of edges
  • i also lies in its subtree

Input format

  • First line: An integer N
  • Second line: N space-separated integers denoting the elements of A
  • Third line: N space-separated integers denoting the elements of K
  • Next N1 lines: Two integers u and v (1u,vN,u!=v) denoting an edge between them

Output format

Print N lines representing the answer. Here, ith line contains the distance to the closest node j in subtree i that satisfies the condition. If no nodes satisfy the condition, then print 1.

Constraints

1N200000

1Ai109

0Ki109

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

For node 1, the only valid candidate is node 3 since |A1A3|K1, so the answer is distance between nodes 1 and 3 which is 2.

For node 2, the valid candidates are node 2, and node 3, so the minimum of the distances from 2 is 0.

For node 3, there are no valid candidates, so the answer is -1.

Editor Image

?