Unterwave Distance
Time limit5sMemory limit1024 MB
Find the minimum gap between the cubed gravities of an alien and a human system, where one optional device shifts gravity in a neighborhood.
- Level
Medium6 of 10
- Topics
- Math, Sorting, Implementation
- Solved
- No attempts yet
Problem
The year is 2312, and humanity's rush to the stars is now 200 years old. Real-time communication between star systems is still an open problem, and the answer is the unterwave.
Unterwave (UW) communication works as follows. Direct UW links exist between certain pairs of star systems. Two systems without a direct link communicate by hopping along existing links through intermediate systems. No system has more than 20 direct links, but any two systems can communicate, directly or indirectly.
Your company must choose two star systems for its new home offices: one in a human system and one in an alien system. Choose them so that the UW distance, a measure of communication latency, is minimized.
Every star system has a gravity value that affects UW communication. No two star systems have the same gravity. Suppose a communication path passes through the sequence of gravity values, including its source and destination. Then three sequences of terms are defined.
For sequences and , and denote the termwise product and difference.
The UW distance is the absolute value of the sum of the terms of
The UW distance can be quite large. Fortunately, your company has a gravity dispersal device. It may be placed in any single system, where it stays. It reduces that system's gravity by 1 and increases by 1 the gravity of every system directly linked to it. Using the device is optional.
Input
The first line has one integer (), the number of star systems. The next lines describe systems 1 to in the form g d. Here is the gravity value (), and is h for a human system or a for an alien system. There is at least one system of each type, and all values of are distinct.
The next line has one positive integer , the number of direct links. Each of the next lines contains two system numbers separated by a space, meaning those systems are directly linked. Links are bidirectional, and no link appears more than once. No system links directly to more than 20 other systems.
Output
Output the minimum UW distance that can be achieved between an alien system and a human system.