題目:
![](http://static.javashuo.com/static/loading.gif)
題目大意:
給你一顆樹,而後將 n (n 確保是偶數) 個點 分紅 n / 2 對,使得這 n / 2 對之間的路徑長度之和最小。
析題得侃:
![](http://static.javashuo.com/static/loading.gif)
Code:
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 2e5 + 10;
typedef long long LL;
// 建反向邊必定要開 2 倍空間
int head[maxn],Next[maxn],edge[maxn],ver[maxn];
int size[maxn];
int t,n,tot;
int u,v,w;
LL res = 0;
void add(int u,int v,int w) {
ver[++ tot] = v,edge[tot] = w;
Next[tot] = head[u],head[u] = tot;
return ;
}
void DFS(int s,int fa,LL sum) {
for(int i = head[s]; i; i = Next[i]) {
int y = ver[i];
if(y != fa) {
// 咱們傳的權值只須要是 該節點到子節點大小便可
DFS(y,s,edge[i]);
// 是當前節點的總大小,因此應該加上 全部子節點的大小
size[s] += size[y];
}
}
// 判斷節點大小是不是 奇數
if(size[s] & 1) res += sum;
return ;
}
int main(void) {
scanf("%d",&t);
while(t --) {
// 多組測試,必定要記得初始化
tot = 0;
memset(head,0,sizeof(head));
scanf("%d",&n);
for(int i = 1; i <= n; i ++) {
size[i] = 1;
}
for(int i = 1; i < n; i ++) {
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
res = 0;
DFS(1,-1,0);
printf("%lld\n",res);
}
return 0;
}