RXD and dividing

RXD and dividing

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 1693    Accepted Submission(s): 732


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 SiSj= .
Then he calulates res=ki=1f({1}Si) .
He wants to maximize the res .
1kn106
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 n1 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 n100 .
 

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
 

题意:

     给定一棵有n个结点的树和一个值k,要求将2~n结点分成k部分,然后再分别与1结点相连,形成的每一棵树都是一棵最小斯坦纳树,求最大价值。


思路:

     求价值最大,即是求如何分配2~n可以使得每条边利用的次数尽可能多。i到其父结点的边,其利用的次数与两个方面有关,一个是分割的块数k,一个是i的子结点数。其中遍历子结点时,我们采用广搜的方法。细想可知,最大的次数应该是子结点数+1,(加上其本身)。但是最大利用次数受k制约,无论如何分配其最大利用次数也不会超过k次,故我们应取二者的最小值,再乘以i到其父结点的权值,即为一条边的结果。再累加每一条边即为最终答案。


下面贴上代码:(具体实现过程详见代码注释)

#include<bits/stdc++.h>
using namespace std;

vector<int> edge[2000005];
map<long long,long long> dis[2000005];
long long sk[2000005];

long long n,k;
long long sum;

long long  bfs(long long t,long long f,long long cs)
{
    long long l=edge[t].size(),y;
    sk[t]=1;
    for(long long i=0; i<l; i++)
    {
        y=edge[t][i]; //y遍历edge中的每一个点
        if(y!=f) //f是否是y的父结点,edge里的结点不是父结点时
            sk[t]=sk[t]+bfs(y,t,dis[t][y]); //sk[i]指i到父结点的边最多可以算几次(i的子结点数+1)
    }
    sum=sum+(long long)cs*min(k,sk[t]); //需取sk[i]与k的最小值,cs为i到父结点边的权值
    return sk[t];
}

int main()
{
    while(scanf("%lld%lld",&n,&k)!=EOF)
    {
        long long x,y,z;
        for(long long i=1; i<n; i++)
        {
            scanf("%lld%lld%lld",&x,&y,&z);
            edge[x].push_back(y);
            edge[y].push_back(x);
            dis[x][y]=z; //无向图
            dis[y][x]=z;
        }

        sum=0;
        bfs(1,-1,0);
        printf("%lld\n",sum);

        for(int i=0; i<=n; i++)
        {
            edge[i].clear();
            dis[i].clear();
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值