POJ1330Nearest Common Ancestors最近公共祖先LCA问题
来源:互联网 发布:js点击小图切换大图 编辑:程序博客网 时间:2024/05/26 22:09
用的离线算法Tarjan
该算法的详细解释请戳
http://www.cnblogs.com/Findxiaoxun/p/3428516.html
做这个题的时候,直接把1470的代码copy过来,改了改输入输出。这个的难度比那个低。
#include<cstdio>#include<algorithm>#include<cstring>#include<vector>using namespace std;const int MAXN=10005;int father[MAXN],ancestor[MAXN];bool visit[MAXN];int ans[MAXN];vector<int> map[MAXN];//save the treeint n,t,root,sx,sy;bool indegree[MAXN];//the indegree to find the rootint getfather(int v){//path compression if(father[v]==v)return v; return father[v]=getfather(father[v]);}void aunion(int u,int v){ int fv=getfather(v),fu=getfather(u); father[fv]=fu;}bool isit(int a,int b){ if(a==sx&&b==sy)return true; return false;}void LCA(int id){ int len=map[id].size(); int son; for(int i=0;i<len;i++){ son=map[id][i]; LCA(son); aunion(id,son); } visit[id]=1; if(visit[sy]&&id==sx){ printf("%d\n",father[getfather(sy)]); return; }else{//attention:this way if(visit[sx]&&id==sy){ printf("%d\n",father[getfather(sx)]); return; } }}void init(){ int x,y,z; scanf("%d",&n); //initialize all the vars for(int i=0;i<=n;i++){ map[i].clear(); } memset(visit,0,sizeof(visit)); memset(ans,0,sizeof(ans)); memset(indegree,0,sizeof(indegree)); for(int i=0;i<=n;i++)father[i]=i; for(int i=0;i<n-1;i++){ scanf("%d%d",&x,&y); indegree[y]=1; map[x].push_back(y); } scanf("%d%d",&sx,&sy); for(int i=1;i<=n;i++)if(!indegree[i])root=i;//find the root;warning:the 0}int main(){ int t; scanf("%d",&t); while(t--){ init(); LCA(root); } return 0;}
0 0
- POJ1330Nearest Common Ancestors最近公共祖先LCA问题
- POJ1330Nearest Common Ancestors——最近公共祖先(离线Tarjan)
- LCA问题——最近公共祖先(Least Common Ancestors)
- 【LCA】最近公共祖先问题Lowest Common Ancestors
- 最近公共祖先(Least Common Ancestors,LCA)问题详解
- LCA(Least Common Ancestors)最近公共祖先问题
- LCA(least common ancestors)最近公共祖先
- LCA最近公共祖先(least common ancestors)
- POJ 1470 Closest Common Ancestors【最近公共祖先LCA】
- [POJ 1330]Nearest Common Ancestors(LCA最近公共祖先)
- POJ1330 Nearest Common Ancestors【最近公共祖先】【Tarjan-LCA算法】
- poj1470 Closest Common Ancestors LCA(最近公共祖先)
- 【LCA最近公共祖先】 poj1470 Closest Common Ancestors
- LCA(Least Common Ancestors)最近公共祖先
- poj1330Nearest Common Ancestors(LCA小结)
- 最近公共祖先(least common ancestors algorithm)
- Nearest Common Ancestors(最近公共祖先)
- Closest Common Ancestors+poj+最近公共祖先
- 《高效学习OpenGL》 之 纹理函数(设置绘图模式) glTexEnv()
- 二叉树实验报告
- servlet中使用HttpServletResponseWrapper截获返回的页面内容
- LCA(最近公共祖先)离线算法Tarjan+并查集
- POJ1470Closest Common Ancestors 最近公共祖先LCA 的 离线算法 Tarjan
- POJ1330Nearest Common Ancestors最近公共祖先LCA问题
- mysql
- 数据结构实验:图的操作
- POJ1986 DistanceQueries 最近公共祖先LCA 离线算法Tarjan
- 线段树
- AC题目简解-线段树
- 在C#中调用windows API函数 最大、最小化窗口
- 数论之因子个数的求法
- Cocos2d-X的动画的打击感支持。