记录编号 201665 评测结果 AAAAAAAAAA
题目名称 [ZLXOI 2015][异次元圣战III]ZLX的陨落 最终得分 100
用户昵称 Gravatarwmez 是否通过 通过
代码语言 C++ 运行时间 1.001 s
提交时间 2015-10-31 06:26:46 内存使用 25.48 MiB
显示代码纯文本
  1. #include<cstdio>
  2. #include<vector>
  3. using namespace std;
  4. #define mp make_pair
  5. vector <pair<int,int> >edge[100005];
  6. int fa[100005][31];
  7. int dis[100005][31];
  8. int deep[100005];
  9. int n,q,x,y,z,m;
  10. void DFS(int x)
  11. {
  12. for(int i=0;i<edge[x].size();i++)
  13. {
  14. if(deep[edge[x][i].first])
  15. {
  16. continue;
  17. }
  18. deep[edge[x][i].first]=deep[x]+1;
  19. fa[edge[x][i].first][0]=x;
  20. dis[edge[x][i].first][0]=edge[x][i].second;
  21. DFS(edge[x][i].first);
  22. }
  23. }
  24. int LCA(int x,int y)
  25. {
  26. if(deep[x]<deep[y])
  27. {
  28. x^=y^=x^=y;
  29. }
  30. int i;
  31. for(i=0;(1<<i)<=deep[x];i++);
  32. i--;
  33. int res=0;
  34. for(int j=i;~j;j--)
  35. {
  36. if(deep[x]-(1<<j)>=deep[y])
  37. {
  38. res+=dis[x][j];
  39. x=fa[x][j];
  40. }
  41. }
  42. if(x==y)
  43. {
  44. return res;
  45. }
  46. for(int j=i;~j;j--)
  47. {
  48. if(fa[x][j]!=fa[y][j])
  49. {
  50. res+=dis[x][j]+dis[y][j];
  51. x=fa[x][j];
  52. y=fa[y][j];
  53. }
  54. }
  55. res+=dis[x][0]+dis[y][0];
  56. return res;
  57. }
  58. int main()
  59. {
  60. freopen("ThefallingofZLX.in","r",stdin);
  61. freopen("ThefallingofZLX.out","w",stdout);
  62. scanf("%d%d",&n,&m);
  63. for(int i=1;i<n;i++)
  64. {
  65. scanf("%d%d%d",&x,&y,&z);
  66. edge[x].push_back(mp(y,z));
  67. edge[y].push_back(mp(x,z));
  68. }
  69. deep[1]=1;
  70. DFS(1);
  71. for(int j=1;(1<<j)<=n;j++)
  72. {
  73. for(int i=1;i<=n;i++)
  74. {
  75. dis[i][j]=dis[i][j-1]+dis[fa[i][j-1]][j-1];
  76. fa[i][j]=fa[fa[i][j-1]][j-1];
  77. }
  78. }
  79. scanf("%d",&q);
  80. while(q--)
  81. {
  82. scanf("%d%d",&x,&y);
  83. printf("%d\n",LCA(x,y));
  84. }
  85. return 0;
  86. }