hdu 6060 RXD and dividing(dfs)

RXD and dividing
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 65 Accepted Submission(s): 15
Problem Description
RXD has a tree T, with the size of n. Each edge has a cost.
Define f(S) as the the cost of the minimal Steiner Tree of the set S on tree T.
he wants to divide 2,3,4,5,6,…n into k parts S1,S2,S3,…Sk,
where ⋃Si={2,3,…,n} and for all different i,j , we can conclude that Si⋂Sj=∅.
Then he calulates res=∑ki=1f({1}⋃Si).
He wants to maximize the res.
1≤k≤n≤106
the cost of each edge∈[1,105]
Si might be empty.
f(S) means that you need to choose a couple of edges on the tree to make all the points in S connected, and you need to minimize the sum of the cost of these edges. f(S) is equal to the minimal cost

Input
There are several test cases, please keep reading until EOF.
For each test case, the first line consists of 2 integer n,k, which means the number of the tree nodes , and k means the number of parts.
The next n−1 lines consists of 2 integers, a,b,c, means a tree edge (a,b) with cost c.
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 n≤100.

Output
For 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

题意:
将一棵树里面的点分成k个集合,并在集合里加入一些边使的一个集合里的任意两个点连通,求使得所有加入集合的边的和的最大值

解析:
要是边的和最大,所以要尽可能多地使用这些边。
所以一颗子树里的孩子节点都要尽可能分到不同的集合里。如果k足够大,那么每一棵子树的孩子节点(包括孙子节点)+子树根节点都可以分到不同的集合,那么这棵子树的根节点向上连接的边(就是该节点与其父节点连接的边)被计算了(child+1)次。但k不足够大即(child+1>k),那么子树的孩子节点最多只能被分到k个集合里,所以根节点向上连接的边只被计算了k次,因此边 的计算次数就是min(child+1,k)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#define MAXN 1000010
#define INF 1999999999
using namespace std;
typedef long long ll;

typedef struct node
{
    ll next;
    ll val;
}node;

ll n,k;
vector<node> edge[MAXN];
ll ans;

ll dfs(ll a,ll valu)  //用dfs来算一颗树的所有孩子节点+孙子节点
{
    if(!edge[a].size())
    {
        ans=ans+valu*(0+1);
        return 1;
    }
    ll child=0;
    for(int i=0;i<edge[a].size();i++)
    {
        child+=dfs(edge[a][i].next,edge[a][i].val);
    }
    ll ch=min(child+1,k);    
    ans+=(ch)*valu;

    return child+1;


}

int main()
{
    ll a;
    while(scanf("%lld%lld",&n,&k)!=EOF)
    {
        for(int i=1;i<=n;i++)edge[i].clear();
        for(ll i=0;i<n-1;i++)
        {
            node tmp;
            scanf("%lld%lld%lld",&a,&tmp.next,&tmp.val);
            edge[a].push_back(tmp);
        }
        ans=0;

        dfs(1,0);
        printf("%lld\n",ans);
    }
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值