Landing Fees
Time limit5sMemory limit1024 MB
Given planet fees and permits that link a planet to a range of planets, find the minimum total route cost that connects all planets.
- Level
Medium6 of 10
- Topics
- Minimum spanning tree, Union-find, Segment tree
- Solved
- No attempts yet
Problem
A new budget airline in a distant galaxy is starting interplanetary flights. The galaxy has planets numbered from 1 to . The cost of opening a route with daily flights in both directions between planets and depends only on the landing and takeoff fees of those two planets. Planet has fee , so a route between and costs .

Figure 1: The second test case. Each planet node shows its fee. Routes in the optimal choice are drawn in bold.
The airline wants every planet connected, so that any planet can be reached from any other planet directly or through other planets. Routes cannot be opened between any two planets. They can only be opened between certain pairs. The allowed pairs are given by permits of the form . A permit means that a route can be opened between planet and every planet with .
Find the minimum total cost of opening routes so that all planets are connected.
Input
The first line contains natural numbers and , the number of planets and the number of permits. The second line contains natural numbers separated by spaces, the fee of each planet. The next lines describe the permits. The -th of these lines contains three natural numbers , , and .
The constraints are , , and . Also, is never between and , so either or . Several permits may have the same parameters, and the same route may appear in several permits. The input always allows all planets to be connected.
Output
Print the minimum possible total cost of opening routes.