Hoditi Hribima
InterviewTime limit1sMemory limit2048 MB
Marin and Vedran alternately take edges that strictly lower their own distance to t. Find the longest total length Ivan can force, or -1 if it can go on forever.
- Level
Medium6 of 10
- Topics
- Graph, Shortest path, Dynamic programming
- Solved
- No attempts yet
Problem
Marin and Vedran lead scout teams on a multi-day trip across Slovenia. Their maps show villages numbered from to , including the start village and the target village .
Each of them prepared a route map on their own. Each map is an undirected weighted graph where villages are vertices and paths are edges. In both maps, every village can reach every other village.
During the day, Marin leads the team along one path from his map. In the evening, Vedran leads the team along one path from his map. This repeats day after day until the team reaches the target village , no matter who was leading at that moment.
Ivan secretly wants to cause trouble for them, but Marin and Vedran do not know this. Before each choice, the leader consults Ivan, who recommends a path. To avoid suspicion, the path Ivan picks must satisfy one condition: after walking it, the distance to the target village must decrease strictly. This distance is computed using only the map of the person leading the team at that moment.
Find the largest distance Ivan can lead the team to the target village without anyone becoming suspicious. If Ivan can lead the team forever across Slovenia, print -1.
The expedition starts on day one at village , and Marin leads first.
Input
The first line contains , , and (, ).
Two blocks follow, first Marin's map, then Vedran's map. The first line of each block contains (), the number of paths. Each of the next lines contains three natural numbers , , and (, ), meaning that the map has a path of length between and .
Output
Print the maximum distance Ivan can lead the team, or -1 if the team can be led forever.
Hint
Explanation of the first sample: On day one, Ivan has Marin lead the team from village 1 to village 4. In the evening, Ivan recommends the path between 4 and 2 to Vedran. On day two, Ivan has Marin lead the team from village 2 to village 3, then has Vedran lead it from village 3 to village 2. The same can be repeated every following day, so the route can go on forever.

The first figure is Marin's map, the second is Vedran's map, and the third is the plan Ivan uses to lead them.