配对 51Nod - 1737

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;
}

猜你喜欢

转载自blog.csdn.net/sunyutian1998/article/details/82925907
今日推荐