HDU2586
来源:互联网 发布:阶级和阶层 知乎 编辑:程序博客网 时间:2024/06/05 12:39
一道多次询问的最近公共祖先问题。
#include <iostream>#include <algorithm>#include <vector>#include <cstdio>#include <cstring>using namespace std;const int MAXN = 40000 + 10;struct Edge{ int to,cost; Edge(){}; Edge(int _to,int _cost) :to(_to),cost(_cost){};};vector<Edge> tree[MAXN];vector<Edge> Qes[MAXN];int degree[MAXN];int f[MAXN];bool vst[MAXN];int dist[MAXN];int ancestor[MAXN];int ans[MAXN];int rank[MAXN];int N,M;void init(){ for(int i = 0;i <= N;++i){ degree[i] = 0; f[i] = i; ans[i] = -1; rank[i] = 0; dist[i] = 0; vst[i] = false; ancestor[i] = -1; tree[i].clear(); Qes[i].clear(); }}int Find(int x){ if(x == f[x]) return x; return f[x] = Find(f[x]);}void LCA(int u){ int sz = tree[u].size(); for(int i = 0;i < sz;++i){ Edge& e = tree[u][i]; if(!vst[e.to]){ vst[e.to] = 1; dist[e.to] = dist[u] + e.cost; LCA(e.to); f[e.to] = u; int k = Qes[e.to].size(); for(int j = 0;j < k;++j){ Edge& et = Qes[e.to][j]; if(vst[et.to]&&ans[et.cost] == -1){ //还未遍历到 if(et.to == e.to) ans[et.cost] = 0; else ans[et.cost] = dist[e.to] + dist[et.to] - 2*dist[Find(et.to)]; } } } }}int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d%d",&N,&M); init(); int x,y,c; for(int i = 1;i < N;++i){ scanf("%d%d%d",&x,&y,&c); tree[x].push_back(Edge(y,c)); tree[y].push_back(Edge(x,c)); } for(int i = 0;i < M;++i){ scanf("%d%d",&x,&y); Qes[x].push_back(Edge(y,i)); Qes[y].push_back(Edge(x,i)); } vst[1] = 1; LCA(1); for(int i = 0;i < M;++i){ printf("%d\n",ans[i]); } } return 0;}
0 0
- hdu2586
- HDU2586
- hdu2586
- HDU2586
- hdu2586
- hdu2586 LCA
- hdu2586(LCA)
- hdu2586 lca
- hdu2586 LCA模板
- hdu2586 lca_tarjan的应用
- HDU2586 离线tarjan LCA
- HDU2586 How far away ?
- HDU2586 How far away ?
- hdu2586【How far away ?】
- hdu2586 LCA 离线算法
- HDU2586【LCA在线算法】
- LCA Tarjan模板 HDU2586
- hdu2586 lca+rmq
- 经典算法之七大排序总结篇
- 糊糊论道--对过滤和规则的理解
- 数据库Oracle强化练习之多表查询
- LCD的接口类型详解
- sgu108:Self-numbers II
- HDU2586
- MFC中CEdit控件实现多行,并且可在界面进行修改
- 安装OpenCV:OpenCV 3.0、OpenCV 2.4.8、OpenCV 2.4.9 +VS 开发环境配置(永久配置)
- template <typename T> inline T Vector<T>::min_val() const
- 抽象类的子类可以new
- 2036 改革春风吹满地
- cloudsim--ubuntu下,下载和安装cloudsim
- linux 系统编程-学习笔记8--信号/线程
- C++:STL标准入门汇总