Meeting in the Middle of the Map
Alice lives in city A and Bob lives in city B. Both of them are driving to a festival in city
T, and the kingdom's m roads are all one-way, each with a toll. Alice and Bob planned their
routes together: if, at some point, the rest of Alice's route and the rest of Bob's route use
exactly the same roads, they travel that stretch in one car and pay each of its tolls only once.
Help them pick routes (not necessarily simple paths) that minimize the total toll they pay.
Formally, the kingdom has n cities and m one-way roads; road i goes from u_i to v_i and
costs w_i to use. You must choose a subset S of the roads such that:
- using only roads in
S, there is a route fromAtoT, and - using only roads in
S, there is a route fromBtoT.
The cost of S is the sum of w_i over the roads it contains (each chosen road is paid for once,
no matter which of them uses it, or how many times). Find the minimum possible cost of S, or
report that no such S exists.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5): the number
of cities and the number of one-way roads.
The second line contains three integers A, B, T (1 ≤ A, B, T ≤ n): Alice's city, Bob's
city, and the festival city. These may coincide.
Each of the next m lines contains three integers u_i, v_i, w_i
(1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^9): a one-way road from u_i to v_i
costing w_i. The same ordered pair of cities may appear more than once, with different tolls.
Output
Print one integer: the minimum total toll, or -1 if Alice or Bob cannot reach T at all.
Notes
In the first example, Alice drives 1 → 3 (toll 5) and Bob drives 2 → 3 (toll 1); from city 3
they share a car along 3 → 6 (toll 10). The total is 5 + 1 + 10 = 16. Driving separately the
rest of the way (not sharing 3 → 6) would cost 15 + 11 = 26, and the direct roads
1 → 6 and 2 → 6 cost 100 each, so sharing from city 3 is best.
In the second example, Bob's city has no outgoing roads at all, so Bob can never reach the
festival, and the answer is -1 regardless of Alice's situation.