hkshakib

Untitled

Mar 31st, 2020
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. const int maxx = 3e5+10;
  5. vector<int>g[maxx],cost[maxx];
  6. int d[maxx],edges;
  7. bool vis[maxx];
  8.  
  9. void bfs(int root)
  10. {
  11. for(int i=0; i<=edges; i++)
  12. {
  13. vis[i]=false;
  14. }
  15. queue<int>q;
  16. q.push(root);
  17. d[root]=0;
  18. vis[root]=true;
  19. while(!q.empty())
  20. {
  21. int u = q.front();
  22. q.pop();
  23. for(int i=0; i<g[u].size(); i++)
  24. {
  25. int v = g[u][i];
  26. if(!vis[v])
  27. {
  28. d[v] = d[u]+cost[u][i];
  29. q.push(v);
  30. vis[v]=true;
  31. }
  32. }
  33. }
  34. }
  35. void clr()
  36. {
  37. for(int i=0; i<=edges; i++)
  38. {
  39. g[i].clear();
  40. cost[i].clear();
  41. }
  42. }
  43. int main()
  44. {
  45. int t,cas=1;
  46. cin>>t;
  47. while(t--)
  48. {
  49. cin>>edges;
  50. clr();
  51. for(int i=0; i<=edges; i++)
  52. {
  53. g[i].clear();
  54. cost[i].clear();
  55. }
  56. for(int i=1; i<edges; i++)
  57. {
  58. int u,v,w;
  59. cin>>u>>v>>w;
  60. g[u].push_back(v);
  61. g[v].push_back(u);
  62. cost[u].push_back(w);
  63. cost[v].push_back(w);
  64. }
  65. bfs(1);
  66. int m =0,sn=0;
  67. for(int i=0; i<edges; i++)
  68. {
  69. if(m<d[i])
  70. {
  71. sn = i;
  72. m = d[i];
  73. vis[i] = false;
  74. }
  75. }
  76. bfs(sn);
  77. m=0;
  78. for(int i=0; i<edges; i++)
  79. {
  80. if(m<d[i])
  81. {
  82. m = d[i];
  83. }
  84. }
  85. cout<<"Case "<<cas++<<": "<<m<<endl;
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment