其他分享
首页 > 其他分享> > #寒假1# D - Nearest Common Ancestors

#寒假1# D - Nearest Common Ancestors

作者:互联网

题目

https://vjudge.net/problem/POJ-1330

思路

LCA中的倍增解法

① 用二维数组 t r e e [ x ] [ y ] tree[x][y] tree[x][y]存储这棵树,x为父节点,y为子节点,使用vector便于DFS
② 用de数组确定根节点:深度为0
③ 用h数组确定所有结点的深度:子节点=父节点深度+1
④ 倍增

    fa[ch][0] = rr;
    for (int i = 1; i < 20; ++i)
    {
        fa[ch][i] = fa[fa[ch][i - 1]][i - 1];  //fa[3][2]=fa[10][1]
        //就是3到8的距离是10到8的一半,所以i-1
        //10就是中点那个~
    }

在这里插入图片描述

代码

#include <iostream>
#include <vector>
#include <cstring>

#define MAXX 200005
using namespace std;
vector<int> tree[MAXX];
int h[MAXX];
int de[MAXX];
int fa[MAXX][20];

void DFS(int rr, int ch)
{
    h[ch] = h[rr] + 1;
    fa[ch][0] = rr;
    for (int i = 1; i < 20; ++i)
    {
        fa[ch][i] = fa[fa[ch][i - 1]][i - 1];
    }
    for (int i = 0; i < tree[ch].size(); ++i)
    {
        DFS(ch, tree[ch][i]);
    }
}

int LCA(int a, int b)
{
    if (h[a] < h[b])
        swap(a, b);
    if (a == b)
        return a;
    for (int i = 19; i >= 0; i--)  //同一高度
    {
        if (h[a] - (1 << i) >= h[b])
            a = fa[a][i];
    }
    if (a == b)
        return a;
    for (int i = 19; i >= 0; i--)  //一起跳
    {
        if (fa[a][i] != fa[b][i])
        {
            a = fa[a][i];
            b = fa[b][i];
        }
    }
    return fa[a][0];
}

int main()
{
    int N, n, r;
    cin >> N;
    while (N--)
    {
        //清零*******
        memset(h, 0, sizeof(h)); //两个数组,虽然都是高度,意义不同
        memset(de,0,sizeof de);
        cin >> n;
        for (int i = 0; i < n - 1; ++i)
        {
            int x, y;
            cin >> x >> y;
            tree[x].push_back(y);
            de[y]++;
        }
        for (int i = 1; i <= n; ++i)  //从1开始
        {
            if (de[i] == 0)
            {
                r = i;
                break;
            }
        }
        DFS(0, r);
        int a, b;
        cin >> a >> b;
        cout << LCA(a, b) << endl;
        for (int i = 1; i <= n; ++i)   //清楚
        {
            tree[i].clear();
        }
    }
    return 0;
}

注意

① MAXX取值小了是RE,大了是MLE…CE是因为用了2e5+5
在这里插入图片描述

标签:Nearest,ch,10,int,de,tree,fa,Ancestors,Common
来源: https://blog.csdn.net/weixin_45797295/article/details/114368299