https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1737
想找出這個最大的比對具體方案很困難 但是題目隻要求最大值 是以可以考慮的模糊一些
将兩個點配對 相當于把兩點路徑上所有邊都加了一遍 貪心的想 假設現在有一條邊i 與其讓左右兩棵樹上的點各自比對 不如讓兩子樹互相比對 但是隻能取決于點數少的子樹 節點數多的子樹剩下的點隻能自己比對
枚舉樹上每條邊 看左右兩顆子樹上誰的節點數少 用少的乘邊權 累加
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
struct node1
{
int u;
int v;
ll w;
};
struct node2
{
int v;
ll w;
int next;
};
node1 pre[maxn];
node2 edge[2*maxn];
int first[maxn],sum[maxn],deep[maxn];
int n,num;
void addedge(int u,int v,ll w)
{
edge[num].v=v;
edge[num].w=w;
edge[num].next=first[u];
first[u]=num++;
}
void dfs(int cur,int fa)
{
int i,v;
sum[cur]=1;
for(i=first[cur];i!=-1;i=edge[i].next)
{
v=edge[i].v;
if(v!=fa)
{
deep[v]=deep[cur]+1;
dfs(v,cur);
sum[cur]+=sum[v];
}
}
}
int main()
{
ll ans;
int i;
scanf("%d",&n);
memset(first,-1,sizeof(first));
num=0;
for(i=1;i<=n-1;i++)
{
scanf("%d%d%lld",&pre[i].u,&pre[i].v,&pre[i].w);
addedge(pre[i].u,pre[i].v,pre[i].w);
addedge(pre[i].v,pre[i].u,pre[i].w);
}
dfs(1,0);
ans=0;
for(i=1;i<=n-1;i++)
{
if(deep[pre[i].u]<deep[pre[i].v]) swap(pre[i].u,pre[i].v);
ans+=pre[i].w*(ll)(min(sum[pre[i].u],n-sum[pre[i].u]));
}
printf("%lld\n",ans);
return 0;
}