Countries at War
InterviewTime limit2sMemory limit512 MB
Given directed weighted edges between cities, treat mutually reachable cities as zero-cost (same country), then answer shortest path queries.
- Level
Medium7 of 10
- Topics
- Shortest path, Graph, Union-find, DFS
- Solved
- No attempts yet
Problem
In 2050, after several attempts by an international body to keep the peace, the third world war breaks out. Industrial, commercial and military secrets force every country to run a highly sophisticated spy service, so every city in the world holds at least one spy from each country. A spy has to reach other spies, informants and their own headquarters while on an assignment. There is no safe channel in wartime, so every message goes out encoded and only its recipient reads what it says.
Spies use the one service that still runs during the war, the mail. Each city has one post office. A letter can go straight to the post office of the destination city, or it can pass through other post offices on the way.
The post office in city can send a printed letter directly to the post office in city when the two have a delivery agreement. The agreement fixes the time in hours that the letter needs to travel from to . An agreement in the opposite direction does not have to exist. Without an agreement between and , office relays the letter through as many other offices as it takes.
Some post offices are linked by electronic means such as satellites and optical fiber. Before the war those links reached every office and a letter arrived instantly. Once the war started each country took control of its own electronic communication, so an office can send a letter electronically, that is with no time at all, only to an office in the same country. Offices and are in the same country when a printed letter is delivered from to and also from to .
Your spy service holds every delivery agreement in the world. Find the minimum time to send a letter for several pairs of cities.
Input
The input holds several test cases.
The first line of each test case has two integers separated by a space, the number of cities () and the number of delivery agreements (). Cities are numbered 1 to .
The next lines each hold three integers separated by spaces, , and (, ). An agreement sends a printed letter from city to city , and that letter arrives hours later.
The line after that holds the number of queries (). The following lines each hold two integers separated by a space, and (). For each query, determine the minimum time to send a letter from city to city .
A line where and are both 0 ends the input. That line is not a test case.
Output
For each test case print lines. Line holds the minimum time in whole hours for query . When there is no way to deliver a letter between the two cities of a query, print Nao e possivel entregar a carta on that line, exactly as written and without quotation marks.
After each test case print one blank line.