POJ1470翻译 最近公共祖先

来源:互联网 发布:游戏客户端编程 编辑:程序博客网 时间:2024/06/05 10:02

最近公共祖先

时间限制:2000ms  空间限制:10000K

描述

编写一个程序,以结点对的方式读入一颗有根树。对每一对结点(u,v)程序应该计算出u和v在树中最近的公共祖先。两个结点u和v最近公共祖先w是在树中深度最大的、u和v的公共祖先。一个结点可以是自己的祖先。例:样例1中,结点2的祖先是2和5

输入

从标准输入读取数据。

输入数据描述一颗有根树。形式如下:

结点总数

结点号:(儿子数n) 后继结点标号1...n

...

结点以整数n(n<=900)代表。接下来以描述需要求LCA的节点对:


结点对的数量

(u,v) (x,y)

...

输入文件包含数组数据

在输入文件中,空白字符(如TAB,空格和换行符)可以被自由使用而不影响读入。

输出

对于每对结点的公共祖先,输出它的标号,然后输出共有多少对结点对以它为最近公共祖先。

结果包含多行,应使用标准输出。以结点标号的升序进行输出。格式如下:

标号:次数

样例输入



55:(3) 1 4 21:(0)4:(0)2:(1) 33:(0)6(1 5) (1 4) (4 2)      (2 3)(1 3) (4 3)

样例输出

2:15:5

注释

输入数据大,建议使用scanf读入



Closest Common Ancestors

Time Limit: 2000MSMemory Limit: 10000K

Description

Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u,v) the program determines the closest common ancestor of u and v in the tree. The closest common ancestor of two nodes u and v is the node w that is an ancestor of both u and v and has the greatest depth in the tree. A node can be its own ancestor (for example in Figure 1 the ancestors of node 2 are 2 and 5)

Input

The data set, which is read from a the std input, starts with the tree description, in the form: 

nr_of_vertices 
vertex:(nr_of_successors) successor1 successor2 ... successorn 
...
where vertices are represented as integers from 1 to n ( n <= 900 ). The tree description is followed by a list of pairs of vertices, in the form: 
nr_of_pairs 
(u v) (x y) ... 

The input file contents several data sets (at least one). 
Note that white-spaces (tabs, spaces and line breaks) can be used freely in the input.

Output

For each common ancestor the program prints the ancestor and the number of pair for which it is an ancestor. The results are printed on the standard output on separate lines, in to the ascending order of the vertices, in the format: ancestor:times 
For example, for the following tree: 

Sample Input

55:(3) 1 4 21:(0)4:(0)2:(1) 33:(0)6(1 5) (1 4) (4 2)      (2 3)(1 3) (4 3)

Sample Output

2:15:5

Hint

Huge input, scanf is recommended.


0 0
原创粉丝点击