fork download
  1. #include<bits/stdc++.h>
  2. #include<ext/pb_ds/assoc_container.hpp>
  3. #include<ext/pb_ds/tree_policy.hpp>
  4.  
  5. using namespace std;
  6. using namespace __gnu_pbds;
  7.  
  8.  
  9. #define int long long int
  10. #define f(i,x,n) for(int i=x;i<n;++i)
  11.  
  12. // ============================================================================================================
  13.  
  14. class Graph {
  15.  
  16. int V; //vertices
  17. list<pair<int, int>> *l; //adjacency list list of pointers to list
  18. // since it is a weighted graph hence we are storeing pair
  19. //x --> (y,cost)
  20.  
  21. public:
  22. Graph(int v) {
  23. V = v;
  24. l = new list<pair<int, int>>[V];
  25. }
  26.  
  27. void addEdge(int u, int v, int cost) {
  28. l[u].push_back({v, cost}); //Segmentation fault
  29. l[v].push_back({u, cost});
  30. }
  31.  
  32. int min(int a, int b) {
  33. if (a > b) return b;
  34. else return a;
  35. }
  36.  
  37. int dfsHelper(int n, bool *visited, int *count, int &ans) {
  38.  
  39. visited[n] = true;
  40. int res;
  41. for (auto i = l[n].begin(); i != l[n].end(); ++i) {
  42. if (!visited[n]) {
  43. res = dfsHelper((*i).first, visited, count, ans);
  44. ans += 2 * ((*i).second) * min(res, V - res);
  45. count[n] += res;
  46. }
  47. }
  48. return count[n];
  49. }
  50.  
  51. int dfs() {
  52. bool *visited = new bool[V];
  53. int *count = new int[V]; // count is for storing the count
  54. // of each node
  55.  
  56. for (int i = 0; i < V; ++i) {
  57. visited[i] = false;
  58. count[i] = 1;
  59. }
  60.  
  61. int ans = 0;
  62. dfsHelper(0, visited, count, ans);
  63. return ans;
  64. }
  65. };
  66.  
  67. int32_t main() {
  68.  
  69. int t;
  70. cin >> t;
  71. while (t--) {
  72. int n;
  73. cin >> n;
  74.  
  75. int x, y, z;
  76. Graph g(n);
  77. f(i, 0, n - 1) {
  78. cin >> x >> y >> z;
  79. g.addEdge(x, y, z);
  80. }
  81.  
  82. int ans = g.dfs();
  83.  
  84. cout << ans << endl;
  85. }
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0s 4176KB
stdin
2
4
1 2 3
2 3 2
4 3 2
6
1 2 3
2 3 4
2 4 1
4 5 8
5 6 5
stdout
0
0