Join two kingdoms
Time limit1sMemory limit128 MB
Two trees with up to 40000 nodes each are joined by one uniformly random cross edge, and you must output the expected diameter of the combined tree.
- Level
Medium7 of 10
- Topics
- Tree, Sorting, Prefix sum, Probability
- Solved
- No attempts yet
Problem
The kingdoms of Nlogonia and Quadradonia fought a long and terrible war. Nobody remembers why it started, so historians call it the Almost Completely Meaningless (ACM) war. When the ACM war ended, the two kingdoms decided to strengthen their bonds and avoid more bloodshed, so they asked the International Consortium for the Prevention of Conflicts (ICPC) for advice. The ICPC recommended building exactly one new road between a city of Nlogonia and a city of Quadradonia, so that the two kingdoms can trade and exchange culture.
Nlogonia has cities and Quadradonia has cities. The road system of a kingdom is a set of bidirectional roads, each joining two different cities of that kingdom, and from any city of a kingdom to any other city of the same kingdom there is exactly one path, that is, one sequence of consecutive roads. The size of such a road system is the largest number of roads you must take to travel between two of its cities.
The ICPC did not say which two cities the new road should join, so the citizens worry that the combined road system becomes too large. To rule out a second ACM war you have to show them otherwise. Every road that could be built between the two kingdoms is equally likely to be the one that gets built. Compute the expected size of the resulting road system.
Input
The first line contains two integers and , the number of cities in each of the two kingdoms (). Cities of Nlogonia carry distinct integers from to , and cities of Quadradonia carry distinct integers from to .
Each of the next lines describes one road of Nlogonia with two distinct integers and , meaning that the road joins city and city ().
Each of the following lines describes one road of Quadradonia in the same format, where the distinct integers and mean that the road joins city and city ().
In each kingdom there is exactly one path between every pair of cities.
Output
Print one line with the expected size of the combined road system, given that every possible road joining the two kingdoms is equally likely.
Print exactly three digits after the decimal point and round the digits below that to the nearest value, rounding a value that falls exactly halfway upward. Write all three decimal digits even when the expected value is an integer.