poj 1470(LCA模板题)

Closest Common Ancestors
Time Limit: 2000MS   Memory Limit: 10000K
Total Submissions: 9221   Accepted: 2955

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: 
poj 1470(LCA模板题)_第1张图片

Sample Input

5
5:(3) 1 4 2
1:(0)
4:(0)
2:(1) 3
3:(0)
6
(1 5) (1 4) (4 2)
      (2 3)
(1 3) (4 3)

Sample Output

2:1
5:5

Hint

Huge input, scanf is recommended.

Source

Southeastern Europe 2000
题目: http://poj.org/problem?id=1470
分析:还是很明显的LCA问题,数据比较大,测试模板用,随便加个读入优化就79ms。。。没加居然780++ms,囧。。。那些没加优化的100++ms怎么搞来的,不会阿~~~
代码:
#include<cstdio>
using namespace std;
const int mm=1111111;
const int mn=1111;
int t[mm],p[mm];
int h[mn],q[mn],f[mn],sum[mn];
bool vis[mn];
int i,j,k,c,e,n;
int find(int u)
{
    if(f[u]==u)return u;
    else return f[u]=find(f[u]);
}
bool tarjan(int u)
{
    int i,v;
    for(i=q[u];i;i=p[i])
        if(vis[v=t[i]])++sum[find(v)];
    vis[f[u]=u]=1;
    for(i=h[u];i;i=p[i])
        if(!vis[v=t[i]])tarjan(v),f[v]=u;
    return 0;
}
inline bool get(int &a)
{
    char c;
    while(((c=getchar())<'0'||c>'9')&&c!=EOF);
    if(c==EOF)return 0;
    for(a=0;c>='0'&&c<='9';c=getchar())a=a*10+c-'0';
    return 1;
}
int main()
{
    while(get(n))
    {
        for(i=1;i<=n;++i)sum[i]=h[i]=q[i]=f[i]=vis[i]=0;
        for(c=e=1;c<=n;++c)
        {
            get(i),get(k);
            while(k--)get(j),++f[t[e]=j],p[e]=h[i],h[i]=e++;
        }
        get(k);
        while(k--)
        {
            get(i),get(j);
            t[e]=j,p[e]=q[i],q[i]=e++;
            t[e]=i,p[e]=q[j],q[j]=e++;
        }
        for(i=1;i<=n;++i)
            if(!f[i])tarjan(i);
        for(i=1;i<=n;++i)
            if(sum[i])printf("%d:%d\n",i,sum[i]);
    }
    return 0;
}


你可能感兴趣的:(poj 1470(LCA模板题))