配对

给出一棵n个点的树,将这n个点两两配对,求所有可行的方案中配对两点间的距离的总和最大为多少。
Input
一个数n(1<=n<=100,000,n保证为偶数)
接下来n-1行每行三个数x,y,z表示有一条长度为z的边连接x和y(0<=z<=1,000,000,000)
Output
一个数表示答案
Input示例
6
1 2 1
1 3 1
1 4 1
3 5 1
4 6 1
Output示例
7
//配对方案为(1,2)(3,4)(5,6)
#include <iostream>
#include <vector>
using namespace std;

typedef long long int ll;
const int MAXN = 1e5 + 5;

struct Edge
{
    Edge(int t, int l)
    {
        to = t;
        len = l;
    }
    int to;
    int len;
};

vector<Edge> edges[MAXN];
ll result = 0;
int n;

ll dfs(int u, int prev)
{
    ll num = 1;
    for (int i = 0; i < edges[u].size(); i++)
    {
        int to = edges[u][i].to;
        if (to == prev)
        {
            continue;
        }

        int len = edges[u][i].len;
        ll childNum = dfs(to, u);
        num += childNum;

        childNum = min(childNum, n - childNum);
        result += childNum * len;
    }

    return num;
}

int main()
{
    cin >> n;
    int x, y, z;

    for (int i = 0; i < n-1; i++)
    {
        cin >> x >> y >> z;
        edges[x].push_back(Edge(y, z));
        edges[y].push_back(Edge(x, z));
    }
    dfs(1, -1);
    cout << result << endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值