题目描述
Today HH becomes a designer, and he faces a problem so he asks you for help.
Treeisland is a country with n cities and n−1 two-way road and from any city you can go to any other cities.
HH the designer is going to design a plan to divide n city into n/2 pairs so that the sum of the length between the n/2 pairs city is minimum.
Now HH has finished it but he doesn't know whether it's true so he ask you to calculate it together.
It's guaranteed that n is even.
输入描述:
The first line contains an positive integer T(1≤T≤100), represents there are T test cases.For each test case: The first line contains an positive integer n(1≤n≤10 4), represents the number of cities in Treeisland, it's guarantee that n is even.Then n−1 lines followed. Each line contains three positive integer u, v and len, (u≠v,1≤u≤n,1≤v≤n,1≤len≤10 9)indicating there is a road of length len between u and v.It's guarantee you can get to any city from any city.
输出描述:
For each test case, output in one line an integer, represent the minimum sum of length.
示例1
输入
2 4 1 2 5 2 3 8 3 4 6 6 1 3 5 3 2 3 4 5 4 4 3 9 4 6 10
输出
11 31
说明
In the first example, you can divide them into (1,2), and (3,4), then the minimum sum of length is 5+6=11In the second example, you can divide them into (1,3),(2,4),(5,6), hen the minimum sum of length is 5+(3+9)+(10+4)=31
给出N个点,让我们将其分成n/2对,每对点的贡献值为两点距离,求最小距离和。
思路:
①我们可以YY一下,对于很多种分配方案,我们可以很容易找到一种情况,就是一条边要么对答案有贡献,要么就是没贡献(也就是求两点距离的时候不会走过这样一条边)。
②题目又是在一棵树上做文章,那么我们肯定要想O(n)的复杂度去Dfs怎么做一做能够得到解。
对于一个点u来讲,如果以这个点u作为根的子树的点的个数为奇数的话,我们知道其子树中肯定有一个点,要和外边一个点相配对才行,那么对应从父亲到当前节点u这条边就一定会有贡献。
③那么过程维护一下,对应到一个点的时候,去判定子树的size是否为奇数即可。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#define ll long long int
struct node
{
int from;
int to;
int w;
int next;
}e[350000];
int cont;
int head[150000];
int size[150000];
ll output;
void add(int from,int to,int w)
{
e[cont].to=to;
e[cont].w=w;
e[cont].next=head[from];
head[from]=cont++;
}
void Dfs(int u,int from,int prew)
{
size[u]=1;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
int w=e[i].w;
if(v==from)continue;
Dfs(v,u,w);
size[u]+=size[v];
}
if(size[u]%2==1)output+=prew;
}
int main()
{
int n;
int t;scanf("%d",&t);
while(t--)
{
output=0,cont=0;
scanf("%d",&n);
memset(head,-1,sizeof(head));
for(int i=1;i<=n-1;i++)
{
int x,y,w;scanf("%d%d%d",&x,&y,&w);
add(x,y,w);add(y,x,w);
}
Dfs(1,-1,0);
printf("%lld\n",output);
}
}