POJ1330 最近公共祖先
2015-05-09 11:14
183 查看
寻找最近公共祖先可以说是树结构里相当基础的知识了。最近学了vector,正好可以派上用场。
本题采用双重链表并行上找的方式。即对于两个节点u和v,若u的层次比v深,则u去寻找父亲,否则v去寻找父亲,直至u=v。
程序中的fa[]数组用来记录父节点,step[]用以记录层次,a[]用以记录某一节点的儿子。函数中的findroot()用以寻找根节点,build()用于建立树结构,注意使用迭代器时需加上“vector :: iterator i”。
代码如下:
本题采用双重链表并行上找的方式。即对于两个节点u和v,若u的层次比v深,则u去寻找父亲,否则v去寻找父亲,直至u=v。
程序中的fa[]数组用来记录父节点,step[]用以记录层次,a[]用以记录某一节点的儿子。函数中的findroot()用以寻找根节点,build()用于建立树结构,注意使用迭代器时需加上“vector :: iterator i”。
代码如下:
#include<iostream> #include<vector> #include<cstdio> #include<cstring> using namespace std; const int maxn=10005; int t,n,fa[maxn],step[maxn]; vector<int> a[maxn]; int findroot() { int root; for (int i=1;i<=n;++i) { if (fa[i]==0) { root=i; return root; } } } void build(int ste,int root) { step[root]=ste; vector <int> :: iterator i; for (i=a[root].begin();i != a[root].end();++i) build(ste+1,*i); } int find(int u,int v) { int steu=step[u],stev=step[v]; while (u!=v) { if (steu>stev) { steu--; u=fa[u]; } else { stev--; v=fa[v]; } } return u; } void init() { cin>>t; for (int i=1;i<=t;++i) { cin>>n; int u,v; memset(fa,0,sizeof(fa)); memset(step,0,sizeof(step)); for (int i=1;i<=n;++i) a[i].clear(); for (int i=1;i<=n-1;++i) { cin>>u>>v; fa[v]=u; a[u].push_back(v); } build(0,findroot()); cin>>u>>v; cout<<find(u,v)<<endl; } } int main() { init(); return 0; }
相关文章推荐
- POJ1330 Nearest Common Ancestors【最近公共祖先】【Tarjan-LCA算法】
- POJ 1330 LCA最近公共祖先 离线tarjan算法
- POJ 1330 Nearest Common Ancestors 最近公共祖先模板/在线/离线
- POJ - 1330 Nearest Common Ancestors(LCA最近公共祖先 朴素算法&倍增法)
- poj 1330 最近公共祖先
- poj 1330 Nearest Common Ancestors(最近公共祖先(LCA))
- POJ 1330 最近公共祖先LCA(Tarjan离线做法)
- 【POJ】1330 Nearest Common Ancestors ——最近公共祖先(LCA)
- 树的最近公共祖先——LCA poj1330 hdu2586
- POJ 1330 Nearest Common Ancestors 【最近公共祖先LCA算法+Tarjan离线算法】
- LCA 算法学习 (最近公共祖先)poj 1330
- poj 1330 LCA 最近公共祖先
- POJ 1330 Nearest Common Ancestors 最近公共祖先 欧拉序列RMQ
- POJ 1330 最近公共祖先LCA_Tarjan 【水】
- kyeremal-poj1330-Nearest Common Ancestors-最近公共祖先
- POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA)
- poj 1330(最近公共祖先)
- POJ 1330 Nearest Common Ancestors(最近公共祖先)
- poj 1330 LCA最近公共祖先
- 【LCA倍增模板】【poj1330】最近公共祖先