POJ-1470-Closest Common Ancestors 解题报告

       LCA简单基础入门题。赤裸裸的求LCA的题,不过输入比较麻烦。题意:其实看图加样例就能懂了,不多说了,最后输出每个节点成为括号内节点LCA的节点id和次数,次数为0就不输出了。


       我的解题思路:用Tarjan的离线算法最后把答案哈希输出就ok了,关于此算法的原理等见请看上一个解题报告


       我的解题代码:离线求LCA算法

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>

using namespace std;

#define N 1000

bool root[N];       //判断是否根节点
bool vis[N];
int father[N];      //幷查集使用
int lca[N];         //LCA
int ans[N];
vector <int> e[N];  //存储子节点
vector <int> q[N];  //存储询问
int n, qn;

void InitRead();

int Find(int x);

void DataProcess(int x);

int main()
{
    while (~scanf("%d", &n))
    {
        InitRead();
        for (int i=1; i<=n; ++i)
        {
            if (root[i])
            {
                DataProcess(i);
                break;
            }
        }
        for (int i=1; i<=n; ++i)
        {
            if (ans[i] != 0)
            {
                printf("%d:%d\n", i, ans[i]);
            }
        }
    }
    return 0;
}

void InitRead()
{
    for (int i=0; i<=n; ++i)
    {
        root[i] = true;
        vis[i] = false;
        father[i] = i;
        ans[i] = lca[i] = 0;
        e[i].clear();
        q[i].clear();
    }
    int a, b, c;
    for (int i=0; i<n; ++i)
    {
        scanf("%d:(%d)", &a, &b);
        while (b--)
        {
            scanf("%d", &c);
            e[a].push_back(c);
            root[c] = false;
        }
    }
    scanf("%d", &qn);
    while (qn--)
    {
        scanf(" (%d %d)", &a, &b);
        q[a].push_back(b);
        q[b].push_back(a);
    }
    return;
}

int Find(int x)
{
    int z, y = x;
    while (y != father[y]) y = father[y];
    while (x != father[x])
    {
        z = father[x];
        father[x] = y;
        x = z;
    }
    return y;
}

void DataProcess(int x)
{
    lca[x] = x;
    int size = e[x].size();
    for (int i=0; i<size; ++i)
    {
        DataProcess(e[x][i]);
        father[e[x][i]] = x;
    }
    vis[x] = true;
    size = q[x].size();
    for (int i=0; i<size; ++i)
    {
        if (vis[q[x][i]]) ans[lca[Find(q[x][i])]]++;    //把答案哈希
    }
    return;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值