fork download
  1. /*
  2. Nowadays, people have many ways to save money on accommodation when they are on vacation. One of these ways is exchanging houses with other people.
  3.  
  4. Here is a group of N people who want to travel around the world. They live in different cities, so they can travel to some other people's city and use someone's house temporary. Now they want to make a plan that choose a destination for each person. There are two rules should be satisfied:
  5.  
  6. All the people should go to one of the other people's city.
  7. Two of them never go to the same city, because they are not willing to share a house.
  8. They want to maximize the sum of all people's travel distance. The travel distance of a person is the distance between the city he lives in and the city he travels to. These N cities have N-1 highways connecting them. The travelers always choose the shortest path when traveling.
  9.  
  10. Given the highways' information, it is your job to find the best plan, that maximum the total travel distance of all people.
  11. */
  12. #include<bits/stdc++.h>
  13.  
  14. using namespace std;
  15.  
  16. class graph{
  17. list<pair<int,int>> *l;
  18. int V;
  19.  
  20. public:
  21. graph(int n){
  22. V = n;
  23. l = new list<pair<int,int>> [V];
  24. }
  25.  
  26. void addEdge(int u, int v, int weight, bool bidirectional=true){
  27. l[u].push_back(make_pair(v,weight));
  28.  
  29. if(bidirectional){
  30. l[v].push_back(make_pair(u,weight));
  31. }
  32. }
  33.  
  34. int dfs(int src, bool* visited, int* count_subtree, int &ans){
  35. visited[src] = true;
  36. count_subtree[src] = 1;
  37.  
  38. for(auto x:l[src]){
  39. auto neighbour = x.first;
  40. if(!visited[neighbour]){
  41. count_subtree[src] += dfs(neighbour, visited, count_subtree, ans);
  42. int y = count_subtree[neighbour];
  43. ans += 2*min(y,V-y)*(x.second);
  44. }
  45. }
  46.  
  47. return count_subtree[src];
  48. }
  49.  
  50. void solve(){
  51. bool *visited = new bool[V]{0};
  52. int *count_subtree = new int[V]{0};
  53.  
  54. int ans = 0;
  55. dfs(0, visited, count_subtree,ans);
  56.  
  57. /*for(int i=0;i<V;i++){
  58.   cout << i << " : " << count_subtree[i] << endl;
  59.   }*/
  60.  
  61. cout << ans << endl;
  62. }
  63.  
  64. };
  65.  
  66. int main(){
  67. int t,i=1;
  68. cin>>t;
  69. while(t--){
  70. int n;
  71. cin >> n;
  72.  
  73. graph g(n);
  74.  
  75. for(int i=0;i<n-1;i++){
  76. int x,y,z;
  77. cin>>x>>y>>z;
  78.  
  79. g.addEdge(--x,--y,z);
  80. }
  81. cout << "Case #" << i++ << " ";
  82. g.solve();
  83. }
  84. }
  85.  
Success #stdin #stdout 0s 15240KB
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
Case #1 18
Case #2 62