題目鏈接:https://ac.nowcoder.com/acm/problem/13886
題意:有一棵樹,有n個節點。讓你分成n/2對。所有對之間的距離和最小。
思路:我們儘量讓每條邊不重複經過。那麼對於一棵子樹v。和他的父親節點u。還有之間的邊權w。如果siz[u]%2== 1那麼v就和u連。ans+=w。如果siz[u]%2== 0那麼v和自己的子樹連過了。不加w的貢獻。
#include <bits/stdc++.h>
using namespace std;
#define LL long long
vector<vector<pair<int , LL> > > v(10005);
LL ans=0;
int DFS(int u, int fa, int w){
int cut=1;
for(auto x: v[u]){
if(x.first!=fa){
cut+=DFS(x.first, u, x.second);
}
}
if(cut%2){
ans+=w;
}
return cut;
}
int main(){
int t; scanf("%d", &t);
while(t--){
int n, x, y, z; scanf("%d",&n);
for(int i=1; i<n; i++){
scanf("%d%d%d", &x, &y, &z);
v[x].push_back({y, z});
v[y].push_back({x, z});
}
ans=0;
DFS(1, 0, 0);
for(int i=1; i<=n; i++) v[i].clear();
printf("%lld\n", ans);
}
return 0;
}