You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.6 KiB

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int N = 2e5 + 10;
int T, n, du[N];
struct node {
int to, w;
};
vector<node> c[N];
bool v[N];
int d[N], f[N];
void clean() {
memset(v, 0, sizeof v);
memset(du, 0, sizeof du);
memset(d, 0, sizeof d);
memset(f, 0, sizeof f);
for (int i = 1; i <= n; i++) c[i].clear();
}
void dp(int x) {
v[x] = 1;
int size = c[x].size() - 1;
for (int i = 0; i <= size; i++) {
int to = c[x][i].to, w = c[x][i].w;
if (v[to]) continue;
dp(to);
if (du[to] == 1)
d[x] += w;
else
d[x] += min(d[to], w);
}
return;
}
void dfs(int x) {
v[x] = 1;
int size = c[x].size() - 1;
for (int i = 0; i <= size; i++) {
int to = c[x][i].to, w = c[x][i].w;
if (v[to]) continue;
if (du[x] == 1)
f[to] = d[to] + w;
else
f[to] = d[to] + min(f[x] - min(d[to], w), w);
dfs(to);
}
return;
}
int main() {
cin >> T;
while (T--) {
cin >> n;
clean();
int x, y, z;
for (int i = 1; i < n; i++) {
cin >> x >> y >> z;
c[x].push_back((node){y, z});
c[y].push_back((node){x, z});
du[x]++;
du[y]++;
}
dp(1);
f[1] = d[1];
memset(v, 0, sizeof v);
dfs(1);
int ans = 0;
for (int i = 1; i <= n; i++) ans = max(ans, f[i]);
printf("%d\n", ans);
}
return 0;
}