﻿ TOJ 3033 ZOJ 1141 POJ 1470 Closest Common Ancestors / 最近公-CSS_网页制作-脚本宝典

# TOJ 3033 ZOJ 1141 POJ 1470 Closest Common Ancestors / 最近公

## TOJ 3033 ZOJ 1141 POJ 1470 Closest Common Ancestors / 最近公

Closest Common Ancestors时间限制(普通 Java):2000MS 6000MS 运行内存限制:65536KByte描述Write a program that takes as input a rooted tree and a list of pairs of vertices For
Closest Common Ancestors

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)

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.

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:

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)

2:1
5:5

```#include <stdio.h>
#include <string.h>
#include <vector>
#define MAX 1000
using namespace std;
vector <int> v[MAX];
vector <int> q[MAX];
int degree[MAX];
bool vis[MAX];
int cnt[MAX];
int bin[MAX];

int find(int x)
{
if(x != bin[x])
return bin[x] = find(bin[x]);
return bin[x];
}
void dfs(int u)
{
bin[u] = u;
int len = v[u].size(),i = 0;
for(i = 0;i < len; i++)
{
dfs(v[u][i]);
bin[v[u][i]] = u;
}
vis[u] = true;
len = q[u].size();
for(i = 0;i < len; i++)
{
if(vis[q[u][i]])
cnt[find(q[u][i])]++;
}
}
int main()
{
char s1[10],s2[10],s3[10];
int n,m,i,x,y;
while(scanf("%d",&n)!=EOF)
{
memset(degree,0,sizeof(degree));
memset(vis,false,sizeof(vis));
memset(cnt,0,sizeof(cnt));
for(i = 1;i <= n; i++)
{
v[i].clear();
q[i].clear();
}
for(i = 0;i < n; i++)
{
scanf("%d%1s%1s%d%1s",&x,s1,s2,&m,s3);
while(m--)
{
scanf("%d",&y);
v[x].push_back(y);
degree[y]++;
}
}
scanf("%d",&m);
for(i = 0;i < m; i++)
{

scanf("%1s%d%d%1s",s1,&x,&y,s3);
q[x].push_back(y);
q[y].push_back(x);

}
int root;
for(i = 1;i <= n; i++)
{
if(!degree[i])
{
root = i;
break;
}
}
//printf("%d\n",root);
dfs(root);
for(i = 1;i <= n; i++)
{
if(cnt[i])
{
printf("%d:%d\n",i,cnt[i]);
}
}
}
return 0;
}
```

Tag：

﻿
<