NOI '13 P2 - Tree Count
View as PDFNational Olympiad in Informatics, China, 2013
We know that a rooted tree can be traversed via depth-first search (DFS)
and breadth-first search (BFS) to obtain the DFS and BFS orderings of
their vertices. Two different trees can have the same DFS ordering, and
at the same time their BFS orderings can also be the same. For example,
the following two trees both have a DFS ordering of 1 2 4 5 3 and a BFS
ordering of 1 2 3 4 5.
Given a DFS and BFS ordering, we would like to know the average height
of all rooted trees satisfying the condition. For example, if there are
 different rooted trees simultaneously possessing the DFS and BFS
orderings, and their heights are respectively 
,
then you are asked to output the value of 
.
Input Specification
The first line contains a single positive integer , representing the
number of vertices.
The second line contains  positive integers (each between 
 and 
,
inclusive), representing the DFS ordering.
The third line contains  positive integers (each between 
 and 
,
inclusive), representing the BFS ordering.
The input guarantees that at least one tree satisfying the two orderings
will exist.
Output Specification
Output a single real number, rounded half-up to three places after the decimal point, representing the average height of the trees.
Sample Input
5
1 2 4 5 3
1 2 3 4 5
Sample Output
3.500
Grading
If your output differs from the correct answer by no more than ,
then you will receive full marks on the test case. Otherwise, you will
receive no marks.
Constraints
 of the test cases will satisfy 
;
 of the test cases will satisfy 
;
 of the test cases will satisfy 
;
 of the test cases will satisfy 
.
Hints
If a rooted tree has only one vertex, then its height is . Otherwise,
its height is equal to 
 plus the maximum height across all of the
subtrees rooted at each child.
For any three vertices , 
, and 
 in the tree, if 
 and 
 are
both 
's children, then the relative orders of 
 and 
 in both the
BFS and DFS orderings are the same. That is, either 
 is always before
, or 
 is always after 
.
Problem translated to English by .
Comments