1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
   | const int maxn = 200000 + 10; const int inf = 0x3f; int N;
  class Graph { public:     int tot;     int head[maxn], ver[maxn * 2], nxt[maxn * 2];     int w[maxn * 2];
      void clear() {         tot = 1;         Set(head, 0);         Set(ver, 0);         Set(nxt, 0);         Set(w, 0);     }
      void add(int x, int y, int z) {         ver[++tot] = y;
          w[tot] = z;
          nxt[tot] = head[x];         head[x] = tot;     } };
  Graph G; int deg[maxn], vis[maxn]; int ds[maxn], f[maxn];
  void init() {     G.clear();     Set(deg, 0);     Set(vis, 0);     Set(ds, 0);     Set(f, 0); }
  void dp(int x) {     assert(vis[x] == 0);     ds[x] = 0;     vis[x] = 1;
      for(int i = G.head[x]; i; i = G.nxt[i]) {         int y = G.ver[i];         if(vis[y]) continue;         dp(y);
          if(deg[y] == 1) ds[x] += G.w[i];         else ds[x] += min(G.w[i], ds[y]);     } }
  void initdfs(int root) {     Set(vis, 0);     f[root] = ds[root]; }
  void dfs(int x) {     vis[x] = 1;     for(int i = G.head[x]; i; i = G.nxt[i]) {         int y = G.ver[i];         if(vis[y]) continue;
          int flow = min(ds[y], G.w[i]);         if(deg[x] == 1) f[y] = ds[y] + G.w[i];         else {             f[y] = ds[y] + min(G.w[i], f[x] - flow);         }
          dfs(y);     } }
  int main() {     freopen("input.txt", "r", stdin);     int T;     scanf("%d", &T);
      while (T--) {         init();         scanf("%d", &N);
          _for(i, 1, N) {             int x, y, z;             scanf("%d%d%d", &x, &y, &z);             G.add(x, y, z);             G.add(y, x, z);
              deg[x]++;             deg[y]++;         }
          // then dp         int root = 1;         dp(root);
          initdfs(root);         dfs(root);
          int ans = 0;         _rep(i, 1, N) ans = max(ans, f[i]);
          cout << ans << endl;     } }
   |