Hyperspace Routes
Time limit5sMemory limit64 MB
For each query, find every possible value of the shortest A-to-B path length as the shared hyperspace edge weight x ranges over the positive integers, then report the count and sum, or inf when unbounded.
- Level
Hard9 of 10
- Topics
- Shortest path, Graph, Math, Implementation
- Solved
- No attempts yet
Problem
In the distant future, food is transported between planets along one-way trade routes. Each route directly connects two planets and has a known transit time.
The traders' guild plans to add new routes using a recently discovered technology: hyperspace travel. Hyperspace travel is also one-directional. Because it is still experimental, the hyperspace travel time is not yet known; it is known, however, that it does not depend on the distance between planets, so every hyperspace route takes the same amount of time to traverse. Let this common time be .
The figure below shows a case with three interconnected planets and their transit times. Planets are labelled with positive integers, and the hyperspace travel time is denoted by (the figure depicts the graph of the second test case).

Transit time is measured in days and is always a positive integer; the hyperspace time is likewise a positive integer.
For two planets and , the guild wants to know all possible values of the shortest-path total transit time from to , taken over every possible value of . For example, in the situation above, the shortest trip from planet 2 to planet 1 could take days (when ), or , , , or day (when ).
Input
The first line contains two integers and : the number of planets and the number of routes (, ).
Each of the next lines contains two planet labels and (, ) and the travel time . For a conventional route, is an integer (); for a hyperspace route, is the character x. Several routes may exist between the same pair of planets.
The next line contains an integer , the number of queries ().
Each of the next lines contains two planet labels and (): the guild asks “what are the possible values of the shortest-path transit time from to ?”.
Output
Print lines, one per query.
For each query print two integers: the number of distinct possible values and their sum. If the number of distinct values is unbounded, print only inf on that line instead. If there is no path from to , both the number of distinct values and their sum are (print 0 0).
Notes
Explanation of the first sample:
- There is no path from planet 2 to planet 1, so the answer is
0 0. - For every positive integer , the shortest path from 1 to 3 takes days, so the number of values is unbounded and the answer is
inf. - The shortest path from 1 to 4 can take days (when ), days (when ), or days (when ). There are distinct values and their sum is .
