Tree(LCA模板)
来源:互联网 发布:算法设计与分析难不难 编辑:程序博客网 时间:2024/06/07 23:26
题目:
给出一棵带有边权的树,问两点之间的距离。
输入:
第一行两个整数 n 和 m ,分别表示点数和询问数。
接下来 n-1 行,每行三个整数 x,y,z,表示 x 与 y 通过一条权为 z 的边连接。
接下来 m 行,每行两个整数 x,y,代表一组询问。
输出:
输出 m 行,每行一个整数,对应一组询问的答案。
EG:
in:
3 3
1 2 1
1 3 2
1 2
1 3
2 3
out:
1
2
3
备注:
【数据范围】
对 30% 的输入数据 :1≤n,m≤1000
对 100% 的输入数据 :1≤n,m≤100000;1≤z≤10000
代码:
#include<iostream>#include<cstring>#include<string>#include<cstdio>#include<cstdlib>#include<ctime>#include<cctype>#include<queue>#include<iomanip>#include<set>#include<map>#include<cmath>#include<algorithm>using namespace std;struct node { node *next; int place,cost;} *first[100005],a[200005];int n,m;int f[100005][25],dist[100005],D[100005],c[100005];int l;inline void add(int x,int y,int z) { ++l; a[l].place=y; a[l].cost=z; a[l].next=first[x]; first[x]=&a[l];}int LCA(int x, int y) { if(D[x]<D[y]) swap(x,y); int will=D[x]-D[y]; for(int step=0;will;will>>=1,++step) if(will&1) x=f[x][step]; if(x==y) return x; for(int i=20;i>=0;--i) if(f[x][i]!=f[y][i]) { x=f[x][i]; y=f[y][i]; } return f[x][0];}int main() { memset(f, 0, sizeof(f)); memset(dist, 255, sizeof(dist)); memset(first, 0, sizeof(first)); cin>>n>>m; l=0; for (int i=1;i<n;++i) { int x,y,z; cin>>x>>y>>z; add(x,y,z); add(y,x,z); } dist[1]=0; c[1]=1; D[1]=0; for(int k=1,l=1;l<=k;++l) { int m=c[l]; for(node *x=first[m];x;x=x->next) if(dist[x->place]==-1) { D[x->place]=D[m]+1; dist[x->place]=dist[m]+x->cost; f[x->place][0]=m; c[++k]=x->place; } } for(int i=1;i<=20;++i) for(int j=1;j<=n;++j) if(f[j][i-1]) f[j][i]=f[f[j][i-1]][i-1]; for(int i=1;i<=m;++i) { int x,y; cin>>x>>y; cout<<dist[x]+dist[y]-2*dist[LCA(x, y)]<<endl; } return 0;}
阅读全文
0 0
- Tree(LCA模板)
- 【LCA】Tree
- LCA模板
- LCA模板
- LCA模板
- LCA 模板
- LCA模板
- LCA模板
- LCA模板
- 【模板】LCA
- LCA模板
- 模板--------LCA
- 【模板】LCA
- lca模板
- LCA 模板
- LCA模板
- LCA 模板
- LCA模板
- Oracle查询最近几天,每小时归档日志产生数量--脚本
- Android读取第三方应用列表并卸载
- MathJax 基础 (1):基础语法
- Windows 函数API大全
- Windows Server 2008将在今年具备TLS 1.2功能
- Tree(LCA模板)
- ssh 客户端登陆报 No further authentication methods available
- WebView与JS的交互和优化
- mybatis里#{}和${}的区别
- java--接口(interface\implements)
- poj1651 Multiplication Puzzle
- 查看网站信息
- python3.5安装gensim包报错 scipy
- Hdu 4063