poj1330 LCA離線演算法

2021-06-05 18:58:06 字數 677 閱讀 5235

模版參考:

題目:給定一棵樹,求兩個結點的最近公共祖先。(最基礎的lca問題)

#include #include #include using namespace std;

const int maxn = 10006;

int dp[maxn][15], father[maxn], dep[maxn];

bool hash[maxn], mark[maxn];

int n;

void getdepth(int u)

while (v != u)

}//模版

void dp()

int main()

for (i = 1; i <= n; i++)

if (!hash[i]) break;

father[i] = i;

dep[i] = 0;

for (i = 1; i <= n; i++) //遍歷所有葉節點求結點的深度

if (!mark[i])

getdepth(i);

dp();

scanf ("%d %d", &x, &y);

printf("%d\n", get_nearest_ancestor(x, y));

}return 0;

}

poj1330(LCA最近公共祖先)

題意 求最近公共祖先 思路 之前學習了樹鏈剖分,然後我就用樹鏈剖分的一小部分知識就可以解這個題目了,記錄每個結點的fa和depth。然後查詢時,每次將depth大的結點往上走直到x y。如下 include include include include include include includ...

POJ 1330(LCA 倍增法模板)

題意 q次詢問求兩個點u,v的lca 思路 lca模板題,首先找一下樹的根,然後dfs預處理求lca u,v ac 1 include2 include3 include4 include5 include 6 include 7 include8 include9 include10 using ...

lca離線演算法模板(poj1330驗證)

include include includeusing namespace std int t,n,x,y int sets 20000 bool flag 20000 int find set int x int ans int n int main for int i 1 i for int ...