POJ 1470 Closest Common Ancestors(离线tarjan-LCA)

Description
给出一棵节点数为n的树和q次查询,每次查询a和b的LCA,最后输出每个节点被查询的次数
Input
第一行为一整数n表示树的节点数,之后n行每行输入一个节点的邻接关系,然后是一整数q表示查询次数,最后q行每行两个整数a和b表示查询a和b的LCA
Output
如果某个节点作为查询中两个点的LCA,则输出其被查询的次数
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
Solution
离线所有查询并求出LCA后统计次数即可
Code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 1111
#define maxq 555555
struct Edge
{
    int to,next;
}edge[maxn*2];
struct Query
{
    int to,next,id;
}query[maxq*2];
int f[maxn];
bool vis[maxn];
int ancestor[maxn];
int head1[maxn],tot1;
int head2[maxq],tot2;
int lca[maxq]; 
void init()
{
    tot1=tot2=0;
    memset(head1,-1,sizeof(head1));
    memset(head2,-1,sizeof(head2));
    memset(vis,0,sizeof(vis));
    memset(f,-1,sizeof(f));
    memset(ancestor,0,sizeof(ancestor));
}
int find(int x)
{
    if(f[x]==-1)return x;
    return f[x]=find(f[x]);
}
void unite(int x,int y)
{
    x=find(x),y=find(y);
    if(x!=y)f[x]=y;
}
void add_edge(int u,int v)
{
    edge[tot1].to=v;
    edge[tot1].next=head1[u];
    head1[u]=tot1++;
}
void add_query(int u,int v,int id)
{
    query[tot2].to=v;
    query[tot2].next=head2[u];
    query[tot2].id=id;
    head2[u]=tot2++;
    query[tot2].to=u;
    query[tot2].next=head2[v];
    query[tot2].id=id;
    head2[v]=tot2++;
}
void tarjan(int u)
{
    ancestor[u]=u;
    vis[u]=1;
    for(int i=head1[u];~i;i=edge[i].next)
    {
        int v=edge[i].to;
        if(vis[v])continue;
        tarjan(v);
        unite(u,v);
        ancestor[find(u)]=u;
    }
    for(int i=head2[u];~i;i=query[i].next)
    {
        int v=query[i].to;
        if(vis[v])lca[query[i].id]=ancestor[find(v)];
    }
} 
int main()
{
    int n,q,root,flag[maxn],ans[maxn];
    while(~scanf("%d",&n))
    {
        init();
        memset(flag,0,sizeof(flag));
        memset(ans,0,sizeof(ans));
        int u,v,num;
        for(int i=1;i<=n;i++)
        {
            scanf("%d:(%d)",&u,&num);
            while(num--)
            {
                scanf("%d",&v);
                add_edge(u,v),add_edge(v,u);
                flag[v]=1;
            }
        }
        scanf("%d",&q);
        for(int i=1;i<=q;i++)
        {
            char ch;
            cin>>ch;
            scanf("%d %d)",&u,&v);
            add_query(u,v,i);
        }
        for(int i=1;i<=n;i++)
            if(!flag[i])
            {
                root=i;
                break;
            }
        tarjan(root);
        for(int i=1;i<=q;i++)
            ans[lca[i]]++;
        for(int i=1;i<=n;i++)
            if(ans[i])printf("%d:%d\n",i,ans[i]);
    }
    return 0;
}

你可能感兴趣的:(POJ 1470 Closest Common Ancestors(离线tarjan-LCA))