Advertisement
AquaBlitz11

Capital

Apr 8th, 2019
732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 100010;
  5. using pii = pair<int, int>;
  6.  
  7. vector<pii> G[N];
  8. int mx = 0;
  9.  
  10. void dfs(int u, int p, int d) { // u = current node, p = parent, d = current distance
  11.     // don't need to check visited because graph is a tree, there's only one way to go back (through parent)
  12.     mx = max(mx, d);
  13.     for (auto v : G[u]) {
  14.         if (v.first != p) // don't go back to parent
  15.             dfs(v.first, u, d+v.second); // go from u to v, so distance += weight of edge (u,v)
  16.     }
  17. }
  18.  
  19. int main()
  20. {
  21.     int n;
  22.     scanf("%d", &n);
  23.     for (int i = 0; i < n-1; ++i) {
  24.         int u, v, w;
  25.         scanf("%d%d%d", &u, &v, &w);
  26.         G[u].push_back({v, w});
  27.         G[v].push_back({u, w});
  28.     }
  29.     dfs(1, 0, 0);
  30.     printf("%d\n", mx);
  31.    
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement