# POJ1470 - Closest Common Ancestors - (LCA tarjan)

2021/8/21 20:32:22 浏览：

# POJ1470 - Closest Common Ancestors

• 链接 Closest Common Ancestors
• 贴一个Tarjan算法的讲解：CSDN - creatorx的博客

``````#include <iostream>
#include <algorithm>
#include <cstring>
#include <math.h>
#include <stdio.h>
#include <set>
#include <vector>
using namespace std;

const int N = 1e3+10;
int in[N], fa[N], vis[N], ask[N][N], n, num[N];
vector<int>g[N];

void init(){
memset(in,0,sizeof in);
memset(ask,0,sizeof ask);
memset(vis, 0, sizeof vis);
memset(num, 0 ,sizeof num);
for(int i = 1; i <= n; i++){
g[i].clear();
fa[i] = i;
}
}

int fin(int x){
if(fa[x] == x) return x;
return fa[x] = fin(fa[x]);
}

void lca(int r){
for(int i = 1; i <= n; i++)
if(vis[i] && ask[r][i]) num[fin(i)] += ask[r][i];

vis[r] = 1;
for(int i = 0; i < g[r].size(); i++){
int t = g[r][i];
lca(t);
fa[t] = r;
}
}

int main(){

while(~scanf("%d",&n)){

init();
int x, m, y;

for(int i = 1; i <= n; i++) {
scanf("%d:(%d)",&x,&m);
while(m--){
scanf("%d",&y);
g[x].push_back(y);
in[y] ++;
}
}

scanf("%d",&m);
while(m--){
scanf(" (%d %d)",&x,&y);
ask[x][y] ++, ask[y][x] ++;
}

for(int i = 1; i <= n; i++){
if(!in[i]) lca(i);
}

for(int i = 1; i <= n; i++)
if(num[i]) cout<<i<<':'<<num[i]<<endl;
}
return 0;

}
``````