#include "iostream"
#include "stack"
#include "vector"
#include "string.h"
using namespace std;
const int MAX_V = 100;
vector<int> G[MAX_V]; //图的邻接表
int parent[MAX_V];
int depth[MAX_V];
void addEdge(int from, int to)
{
G[from].push_back(to);
}
void dfs(int v, int p, int d)
{
parent[v] = p;
depth[v] = d;
for(int i=0; i<G[v].size(); i++)
if(G[v][i] != p)
dfs(G[v][i], v, d+1);
}
int lca(int u, int v)
{
//先让两个顶点走到同一深度
while(depth[u] > depth[v])
u = parent[u];
while(depth[v] > depth[u])
v = parent[v];
while(u != v)
{
u = parent[u];
v = parent[v];
}
return u;
}
int main()
{
int G1[8][8] = {
{0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 1},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
};
int i, j;
for(i=0; i<8; i++)
for(j=0; j<8; j++)
if(G1[i][j])
addEdge(i+1, j+1);
dfs(1, -1, 0); //根结点为1, 祖先为-1,深度为0
cout << "4, 7的LCA为:" << lca(4, 7) << endl;
cout << "8, 6的LCA为:" << lca(8, 6) << endl;
cout << "5, 8的LCA为:" << lca(5, 8) << endl;
return 0;
}
LCA
最新推荐文章于 2021-11-07 13:08:55 发布