Description
给出一棵n个点的树,将这n个点两两配对,求所有可行的方案中配对两点间的距离的总和最大为多少。
Solution
贪心的想,有使距离总和最大,每条边乘上的系数就要尽量的大,
设
fx
表示点x的儿子个数,
那每一条边能乘上的最大的系数,就是:
min(n−fx,fx)
复杂度: O(n)
Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define efo(i,q) for(int i=A[q];i;i=B[i][0])
using namespace std;
typedef long long LL;
const int N=100500;
int read(int &n)
{
char ch=' ';int q=0,w=1;
for(;(ch!='-')&&((ch<'0')||(ch>'9'));ch=getchar());
if(ch=='-')w=-1,ch=getchar();
for(;ch>='0' && ch<='9';ch=getchar())q=q*10+ch-48;n=q*w;return n;
}
int m,n;
int B[2*N][3],A[N],B0;
int f[N];
LL ans;
void link(int q,int w,int e)
{
B[++B0][0]=A[q],A[q]=B0,B[B0][1]=w,B[B0][2]=e;
B[++B0][0]=A[w],A[w]=B0,B[B0][1]=q,B[B0][2]=e;
}
int dfs(int q,int fa)
{
f[q]=1;
efo(i,q)if(B[i][1]!=fa)f[q]+=dfs(B[i][1],q),ans+=(LL)min(f[B[i][1]],n-f[B[i][1]])*B[i][2];
return f[q];
}
int main()
{
int q,w,e;
read(n);
fo(i,1,n-1)read(q),read(w),read(e),link(q,w,e);
dfs(1,0);
printf("%lld\n",ans);
return 0;
}