hiho刷题日记——第十七天最近公共祖先·三

问题

还是最近公共祖先问题。

思路

之前用了Tarjan算法来做。但是这里遇到一个问题就是如果只有一个询问,那么将很难决定到底是针对这个询问就直接进行计算还是等待一定数量的询问一起计算。毕竟无论是一个询问还是很多个询问,使用离线算法都是只需要做一次深度优先搜索就可以了的。
所以这一次改用一个在线算法。
先根据输入建立一棵家族树。
建立好家族树之后,深度遍历该树。使用一个数组来记录走过的路径(无论是从父节点进入还是子结点返回都要记录)。
然后这个问题就变为了一个RMQ问题。我们就可以使用RMQ-ST算法来解决了。

代码

#include<cstdio>
#include<iostream> 
#include<cstring>
#include<cmath>
#include<map>
using namespace std;

const int MAX_SIZE=100000+5;
int N;
int head[MAX_SIZE],dep[MAX_SIZE],last[MAX_SIZE],e=0;
int rmq[20][MAX_SIZE<<1],rmq_i=0;
int Log2[MAX_SIZE<<1];
map<string,int> str_id;
map<int,string> id_str;

struct EDGE
{
    int v,next;
}edge[MAX_SIZE];

void addEdge(int x,int y)
{
    edge[e].v=y;
    edge[e].next=head[x];
    head[x]=e++;
}

void dfs(int cur,int dp)
{
    dep[cur]=dp;
    last[cur]=rmq_i;//这句话之前没写。查错查了我一天。哭死。
    rmq[0][rmq_i++]=cur;
    int p=head[cur];
    while(p!=-1)
    {
        dfs(edge[p].v,dp+1);
        last[cur]=rmq_i;
        rmq[0][rmq_i++]=cur;
        p=edge[p].next;
    }

}

int main()
{
    memset(head,-1,sizeof(head));
    int id=0;
    string fn,sn;
    scanf("%d",&N);
    while(N--)
    {
        cin>>fn>>sn;
        if(!str_id.count(fn)) 
        {
            str_id[fn]=id;
            id_str[id]=fn;
            id++;
        }
        if(!str_id.count(sn))
        {
            str_id[sn]=id;
            id_str[id]=sn;
            id++;
        }
        addEdge(str_id[fn],str_id[sn]);
    } 
    dfs(0,0);

    int t=2,v=0;
    Log2[0]= Log2[1]=0;
    for(register int i=1;i<rmq_i;i++)   
    {
        if(i>t) {t<<=1;v++;}
        Log2[i]=v;
    }

    t=1;
    for(register int len=1;len<=Log2[rmq_i-1];len++)
    {
        for(int l=0;l+t<rmq_i;l++)
        {
            if(dep[rmq[len-1][l]]<dep[rmq[len-1][l+t]])
                rmq[len][l]=rmq[len-1][l];
            else rmq[len][l]=rmq[len-1][l+t];
        }
        t<<=1;
    }

    scanf("%d",&N);
    int l,r,len;
    while(N--)
    {
        cin>>fn>>sn;
        if(last[str_id[fn]]>last[str_id[sn]])
        {
            l=last[str_id[sn]];
            r=last[str_id[fn]];
        }
        else
        {
            l=last[str_id[fn]];
            r=last[str_id[sn]];
        }

        len=Log2[r+1-l];
        if(dep[rmq[len][l]]>dep[rmq[len][r+1-(1<<len)]])
            cout<<id_str[rmq[len][r+1-(1<<len)]]<<endl;
        else cout<<id_str[rmq[len][l]]<<endl;
    }
    return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值