main.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <vector>
  4. // For g++ only
  5. #define FOREACH(i, a) for (__typeof(a.end()) i = a.begin(); i != a.end(); ++i)
  6. using namespace std;
  7. const int N = 200000;
  8. // dp[i] means the max flow form node i to its subtree in [bottom-up dfs],
  9. // if sub(i) means the sub nodes of node i, cap(i, j) means the cap of
  10. // edge i -> j, deg(i) means the degree of node i, then we have:
  11. // for j in sub(i),
  12. // dp[i] = dp[i] + cap(i, j), if deg(j) == 1
  13. // = dp[i] + min(cap(i, j), dp[j]), if deg(j) > 1
  14. // (init state: dp[i] = 0)
  15. // In [top-down dfs], we have:
  16. // for j in sub(i),
  17. // dp[j] = dp[j] + cap(i, j), if deg(i) == 1
  18. // = dp[j] + min(cap(i, j) , dp[i] - min(cap(i, j), dp[j])), if deg(i) > 1
  19. // init state: dp[root] = dp[root]
  20. int dp[N + 1];
  21. vector<pair<int, int> > adj[N + 1];
  22. void bottom_up(int u, int p) {
  23. FOREACH(e, adj[u]) {
  24. int v = e->first;
  25. if (v == p) continue;
  26. bottom_up(v, u);
  27. if (adj[v].size() == 1)
  28. dp[u] += e->second;
  29. else
  30. dp[u] += min(dp[v], e->second);
  31. }
  32. }
  33. void top_down(int u, int p) {
  34. int deg = adj[u].size();
  35. FOREACH(e, adj[u]) {
  36. int v = e->first;
  37. if (v == p) continue;
  38. if (deg == 1)
  39. dp[v] += e->second;
  40. else
  41. dp[v] += min(e->second, dp[u] - min(e->second, dp[v]));
  42. top_down(v, u);
  43. }
  44. }
  45. int main() {
  46. int t, n, u, v, w;
  47. scanf("%d", &t);
  48. while (t--) {
  49. scanf("%d", &n);
  50. for (int i = 1; i <= n; i++) adj[i].clear();
  51. memset(dp, 0, sizeof(dp));
  52. for (int i = 0; i < n - 1; i++) {
  53. scanf("%d %d %d", &u, &v, &w);
  54. adj[u].push_back(make_pair(v, w));
  55. adj[v].push_back(make_pair(u, w));
  56. }
  57. bottom_up(1, 0);
  58. top_down(1, 0);
  59. int ans = 0;
  60. for (int i = 1; i <= n; i++) ans = max(ans, dp[i]);
  61. printf("%d\n", ans);
  62. }
  63. return 0;
  64. }