Round Trip
Time limit1sMemory limit128 MB
Find a non-descending path from town 1 to town n and a non-ascending path back, sharing the first-visit visa fee of each town, minimizing total road cost plus fees.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
Jim plans to visit one of his best friends, who lives in a town in the mountains. He first leaves his hometown and travels to the destination town; this is the go phase. He then travels back to his hometown; this is the return phase. Write a program that computes the minimum total cost of the whole trip, where the total cost is the sum of the cost of the go phase and the cost of the return phase.
The towns form a network that includes the hometown and the destination. Every road is one-way and may be traveled only in its given direction. Traveling a road costs a fixed amount.
Besides the road costs, you must pay a visa fee to pass through each town along the way. Because it is a visa fee, you pay it only on your first visit to a town; the second and later visits to the same town are free.
Each town has an altitude. During the go phase you may not descend: when moving from town to town , the altitude of must not exceed that of . During the return phase you may not ascend: the altitude of must not be less than that of . If and have equal altitude, the road from to may be used in both phases.
Input
The input consists of several datasets. Each dataset has the following format.
n m
d2 e2
d3 e3
...
d(n-1) e(n-1)
a1 b1 c1
a2 b2 c2
...
am bm cm
Every value is a non-negative integer, and values on the same line are separated by a single space.
is the number of towns and is the number of one-way roads, with and . Towns are numbered through . Town is the hometown and town is the destination.
For each town with , is its visa fee and is its altitude, with and . Towns and charge no visa fee. The altitude of town is and the altitude of town is . Several towns may share the same altitude, but at most towns share any single altitude.
The -th road goes from town to town and costs , with , , and . You may travel from to but not from to unless a separate road is given. No two roads share the same ordered pair of endpoints, and no road connects a town to itself.
The last dataset is followed by a line containing two zeros separated by a space; that line is not part of the data to process.
Output
For each dataset, output a single line containing the minimum total cost of the trip, including visa fees. If no valid trip exists, output .