[关闭]
@xiaoziyao 2020-03-26T21:32:01.000000Z 字数 1568 阅读 1667

Timus Online Judge(Ural)1471 Distance in the Tree题解

Timus


题目简述:2/3/4/3/lca

传送门:1471. Distance in the Tree

题面

A weighted tree is given. You must find the distance between two given nodes.
Input

输入

The first line contains the number of nodes of the tree n (1 ≤ n ≤ 50000). The nodes are numbered from 0 to n – 1. Each of the next n – 1 lines contains three integers u, v, w, which correspond to an edge with weight w (0 ≤ w ≤ 1000) connecting nodes u and v. The next line contains the number of queries m (1 ≤ m ≤ 75000). In each of the next m lines there are two integers.

输出

For each query, output the distance between the nodes with the given numbers.

样例

input:
3
1 0 1
2 0 1
3
0 1
0 2
1 2
output:
1
1
2

分析

题意:给定一棵n()个点的树,求m()次询问任意两点树上距离

可以一边dfs求树上每个点与根的距离,顺便做lca预处理,然后就很显然是lca裸题了

代码

  1. #include<stdio.h>
  2. const int maxn=1000005;
  3. int i,j,k,m,n,s,e;
  4. int start[maxn],to[maxn],then[maxn],worth[maxn],dis[maxn],dep[maxn],fore[maxn][40];
  5. inline void add(int x,int y,int z){
  6. then[++e]=start[x],start[x]=e,to[e]=y,worth[e]=z;
  7. }
  8. void dfs(int x,int last){
  9. dep[x]=dep[last]+1,fore[x][0]=last;
  10. for(int i=1;i<=30;i++)
  11. fore[x][i]=fore[fore[x][i-1]][i-1];
  12. for(int i=start[x];i;i=then[i]){
  13. int y=to[i];
  14. if(y==last)
  15. continue;
  16. dis[y]=dis[x]+worth[i];
  17. dfs(y,x);
  18. }
  19. }
  20. int lca(int a,int b){
  21. if(dep[a]<dep[b])
  22. a+=b,b=a-b,a-=b;
  23. for(int i=30;i>=0;i--)
  24. if(dep[fore[a][i]]>=dep[b])
  25. a=fore[a][i];
  26. if(a==b)
  27. return a;
  28. for(int i=30;i>=0;i--)
  29. if(fore[a][i]!=fore[b][i])
  30. a=fore[a][i],b=fore[b][i];
  31. return fore[a][0];
  32. }
  33. int main(){
  34. scanf("%d",&n);
  35. for(i=1;i<n;i++){
  36. int x,y,z;
  37. scanf("%d%d%d",&x,&y,&z);
  38. add(x,y,z),add(y,x,z);
  39. }
  40. dfs(s,0);
  41. scanf("%d",&m);
  42. for(i=1;i<=m;i++){
  43. int a,b,c;
  44. scanf("%d%d",&a,&b);
  45. c=lca(a,b);
  46. printf("%d\n",dis[a]+dis[b]-dis[c]*2);
  47. }
  48. return 0;
  49. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注