main.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // In [top-down dfs], we have:
  15. // for j in sub(i),
  16. // dp[j] = dp[j] + cap(i, j), if deg(i) == 1
  17. // = dp[j] + min(cap(i, j) , dp[i] - min(cap(i, j), dp[j])), if deg(i) > 1
  18. int dp[N + 1];
  19. vector<pair<int, int> > adj[N + 1];
  20. void bottom_up(int u, int p) {
  21. FOREACH(e, adj[u]) {
  22. int v = e->first;
  23. if (v == p) continue;
  24. bottom_up(v, u);
  25. if (adj[v].size() == 1)
  26. dp[u] += e->second;
  27. else
  28. dp[u] += min(dp[v], e->second);
  29. }
  30. }
  31. void top_down(int u, int p) {
  32. int deg = adj[u].size();
  33. FOREACH(e, adj[u]) {
  34. int v = e->first;
  35. if (v == p) continue;
  36. if (deg == 1)
  37. dp[v] += e->second;
  38. else
  39. dp[v] += min(e->second, dp[u] - min(e->second, dp[v]));
  40. top_down(v, u);
  41. }
  42. }
  43. int main() {
  44. int t, n, u, v, w;
  45. scanf("%d", &t);
  46. while (t--) {
  47. scanf("%d", &n);
  48. for (int i = 1; i <= n; i++) adj[i].clear();
  49. memset(dp, 0, sizeof(dp));
  50. for (int i = 0; i < n - 1; i++) {
  51. scanf("%d %d %d", &u, &v, &w);
  52. adj[u].push_back(make_pair(v, w));
  53. adj[v].push_back(make_pair(u, w));
  54. }
  55. bottom_up(1, 0);
  56. top_down(1, 0);
  57. int ans = 0;
  58. for (int i = 1; i <= n; i++) ans = max(ans, dp[i]);
  59. printf("%d\n", ans);
  60. }
  61. return 0;
  62. }