您的位置:首页 > 其它

POJ-1470-Closest Common Ancestors 解题报告

2014-10-22 16:18 399 查看
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
;       //判断是否根节点
bool vis
;
int father
;      //幷查集使用
int lca
;         //LCA
int ans
;
vector <int> e
;  //存储子节点
vector <int> q
;  //存储询问
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: