Primary Factor
Time limit3sMemory limit1024 MB
Given a graph with node heights, compute for each node the minimum descent needed to reach a strictly taller node, or its own height if none exists.
- Level
Medium7 of 10
- Topics
- Graph, Greedy, Union-find, Sorting
- Solved
- No attempts yet
Problem
"Which is the highest mountain in the world? The highest point on the summit of Mount Everest. OK, but which is the second highest mountain in the world? The second highest point on the summit of Mount Everest, of course."
With that logic, the list of the world's highest mountains becomes very silly. But there is a solution: introduce the concept of a primary factor. The primary factor of a mountain is the smallest height difference you must descend from the mountain to reach a strictly higher mountain. It works as a kind of measure of how independent a mountain is, and if you remove every point with a primary factor less than 200 m, you get rid of all the silly little mountains that really sit on higher mountains. This problem is about finding all primary factors in a graph.
We have a graph with nodes and edges, where each node has a non-negative integer , the height of the node. The primary factor of a node is the smallest height you must descend from the node to reach a node of strictly greater height. Here is a slightly more mathematical definition: let be the set of all paths from node to some other node such that . The primary factor of is defined as
If , that is, if it is impossible to reach a node of greater height at all, we say that the primary factor is .
Given a graph, find the primary factors of all nodes.
Input
One line with two integers, and . One line with integers , the heights of the nodes. lines with two integers, and (), meaning that an edge goes between nodes and .
Output
One line with integers, the primary factors of the nodes.