HDU:6060 RXD and dividing (DFS)

本文探讨了一个特定的图论问题——如何将树的节点进行分组以最大化特定函数的累加值。通过深入分析问题背景及特点,采用DFS深度优先搜索算法结合最小Steiner树概念来高效解决这一挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RXD has a tree TT, with the size of nn. Each edge has a cost. 
Define f(S)f(S) as the the cost of the minimal Steiner Tree of the set SS on tree TT
he wants to divide 2,3,4,5,6,n2,3,4,5,6,…n into kk parts S1,S2,S3,SkS1,S2,S3,…Sk
where Si={2,3,,n}⋃Si={2,3,…,n} and for all different i,ji,j , we can conclude that SiSj=Si⋂Sj=∅
Then he calulates res=ki=1f({1}Si)res=∑i=1kf({1}⋃Si)
He wants to maximize the resres
1kn1061≤k≤n≤106 
the cost of each edge[1,105]the cost of each edge∈[1,105] 
SiSi might be empty. 
f(S)f(S) means that you need to choose a couple of edges on the tree to make all the points in SS connected, and you need to minimize the sum of the cost of these edges.f(S)f(S) is equal to the minimal cost 
InputThere are several test cases, please keep reading until EOF. 
For each test case, the first line consists of 2 integer n,kn,k, which means the number of the tree nodes , and kk means the number of parts. 
The next n1n−1 lines consists of 2 integers, a,b,ca,b,c, means a tree edge (a,b)(a,b) with costcc
It is guaranteed that the edges would form a tree. 
There are 4 big test cases and 50 small test cases. 
small test case means n100n≤100.OutputFor each test case, output an integer, which means the answer.Sample Input
5 4
1 2 3
2 3 4
2 4 5
2 5 6
Sample Output
27

        题意:将一颗树的2~n分成k块,求1到各块的最大权值

        方法:由于每个点与它父节点的贡献为min(num[i],k),所以求出每个节点的子节点+1,并记录该节点的权值

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=1000000+10;
int dist[N],num[N],head[N],cnt;
struct node
{
    int v,next;
}edges[N];
void add(int u,int v,int w)
{
    edges[cnt].v=v;
    edges[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int u,int pre)
{
    num[u]=1;
    for(int i=head[u];i!=-1;i=edges[i].next)
    {
        int v=edges[i].v;
        dfs(v,u);
        num[u]+=num[v];
    }
}
int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k))
    {
        cnt=0;
        memset(head,-1,sizeof(head));
        for(int i=1;i<n;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            dist[v]=w;
            add(u,v,w);
        }
        dfs(1,0);
        long long sum=0;
        for(int i=2;i<=n;i++)
            sum+=(long long)dist[i]*min(num[i],k);
        printf("%lld\n",sum);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值