Closest Common Ancestors
Time Limit: 2000MS | Memory Limit: 10000K | |
Total Submissions: 14314 | Accepted: 4607 |
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.
Source
模板题:
给出在线做法和离线做法:
在线的DFS+RMQ做法:
1 //444K 485MS C++ 2082B 2014-04-15 19:41:38 2 #include3 #include 4 #include 5 #define N 1005 6 struct node{ 7 int u,v; 8 int next; 9 }edge[2*N];10 int n,num,to,head[N];11 int set[2*N],dep[2*N];12 int rank[N],vis[N];13 int dp[2*N][30];14 void addedge(int u,int v)15 {16 edge[num].u=u;17 edge[num].v=v;18 edge[num].next=head[u];19 head[u]=num++;20 }21 int Min(int a,int b)22 {23 return dep[a] y) return set[RMQ(y,x)];59 else return set[RMQ(x,y)];60 }61 int main(void)62 {63 int m,u,v,mm;64 int in[N];65 while(scanf("%d",&n)!=EOF)66 {67 memset(in,0,sizeof(in));68 memset(vis,0,sizeof(vis));69 memset(head,-1,sizeof(head));70 num=0;71 for(int i=0;i
离线的Tarjan做法:
1 //3024K 563MS C++ 1575B 2014-04-15 20:32:44 2 //Runtime Error 了好几次 T T 3 #include4 #include 5 #include 6 #define N 1005 7 using namespace std; 8 vector child[N],V[N]; 9 int set[N],vis[N];10 int in[N];11 int n;12 void init()13 {14 for(int i=0;i<=n;i++){15 child[i].clear();16 V[i].clear();17 }18 memset(vis,0,sizeof(vis));19 memset(in,0,sizeof(in));20 }21 int find(int x)22 {23 if(set[x]!=x) set[x]=find(set[x]);24 return set[x];25 }26 void merge(int a,int b)27 {28 int x=find(a);29 int y=find(b);30 set[y]=x;31 }32 void LCA(int u)33 {34 set[u]=u;35 vis[u]=true;36 for(int i=0;i