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
【题意】
求LCA。【分析】
跟上一题差不多,注意输入,没有那么复杂的。
代码如下:
1 #include2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 #define Maxn 10010 8 #define INF 100000000 9 10 int fa[Maxn],first[Maxn],size[Maxn],dep[Maxn],son[Maxn]; 11 int w[Maxn],top[Maxn];int wl; 12 bool q[Maxn]; 13 int sum[Maxn]; 14 15 struct node 16 { 17 int x,y,next; 18 }t[2*Maxn];int len; 19 20 int mymax(int x,int y) { return x>y?x:y;} 21 int mymin(int x,int y) { return x size[son[x]]) son[x]=t[i].y; 38 } 39 } 40 41 void dfs2(int x,int tp) 42 { 43 w[x]=++wl; 44 top[x]=tp; 45 if(size[x]!=1) dfs2(son[x],tp); 46 for(int i=first[x];i;i=t[i].next) if(t[i].y!=fa[x]&&t[i].y!=son[x]) 47 { 48 dfs2(t[i].y,t[i].y); 49 } 50 } 51 52 int LCA(int a, int b) 53 { 54 while (1) 55 { 56 if(top[a]==top[b]) return dep[a]<=dep[b]?a:b; 57 else if(dep[top[a]]>=dep[top[b]]) a=fa[top[a]]; 58 else b=fa[top[b]]; 59 } 60 } 61 62 63 64 int main() 65 { 66 int n; 67 while(scanf("%d",&n)!=EOF) 68 { 69 memset(first,0,sizeof(first)); 70 memset(q,0,sizeof(q)); 71 len=0; 72 for(int i=1;i<=n;i++) 73 { 74 int x,y,z; 75 scanf("%d:(%d) ",&x,&y); 76 while(y--) 77 { 78 scanf("%d",&z); 79 ins(x,z);q[z]=1; 80 } 81 } 82 int root; 83 for(int i=1;i<=n;i++) if(!q[i]) root=i; 84 dep[0]=0;size[0]=0; 85 dfs1(root,0);wl=0; 86 dfs2(root,root); 87 int m; 88 scanf("%d",&m);getchar(); 89 memset(sum,0,sizeof(sum)); 90 for(int i=1;i<=m;i++) 91 { 92 int x,y; 93 scanf(" (%d %d)",&x,&y); 94 sum[LCA(x,y)]++; 95 } 96 for(int i=1;i<=n;i++) if(sum[i]!=0) 97 printf("%d:%d\n",i,sum[i]); 98 } 99 return 0;100 }
2016-05-10 13:14:31