Journey
Time limit2sMemory limit512 MB
Two weighted graphs share vertices; alternate one edge per graph, each strictly decreasing that graph's distance to t, and find the longest total route or -1 if infinite.
- Level
Hard8 of 10
- Topics
- Shortest path, Dynamic programming, Graph, Greedy
- Solved
- No attempts yet
Problem
An army marches from the city of Kostroma to the village of Domino. Two generals, Stefan and Konstantin, lead it.
The generals carry different maps of the same region. The villages sit at the same places on both maps, but Stefan's map records only the main roads and Konstantin's map records only the narrow side paths. Walking a main road by day is dangerous, so the generals move the army like this. At night they follow one main road from Stefan's map, and by day they follow one side path from Konstantin's map.
A spy named Susanin marches with the army. He studies both maps and decides which road each general picks. His aim is to make the march to Domino as long as he can. Moving in a direction that has nothing to do with Domino would expose him, so Susanin only picks a road along which the shortest distance to the destination strictly decreases. The road he picks for Stefan must decrease the shortest distance to Domino measured with the main roads alone, and the road he picks for Konstantin must decrease the shortest distance to Domino measured with the side paths alone.

Find the length of the longest route Susanin can produce.
Input
The first line contains the number of villages on the maps , the number of the city of Kostroma where the march starts, and the number of the village of Domino where the march ends. (, , ) The villages are numbered from to .
Two blocks follow in this order, one for Stefan's map and one for Konstantin's map.
The first line of each block contains the number of roads . ()
Each of the next lines contains three natural numbers , , . This means a bidirectional road of length joins village and village . (, ) Several roads may join the same pair of villages, and a road whose equals its may appear.
Every village is connected on each map, so the roads of a single map already reach every village from every other village. The army starts at village and makes its first move at night, so the first map it uses is Stefan's map. After that it takes one main road each night and one side path each day.
Output
Print the length of the longest route Susanin can produce before the army reaches Domino. The length of a route is the sum of the lengths of every main road and side path used along it. If Susanin can keep the army moving forever without ever reaching Domino, print -1.