1. 程式人生 > >RXD and dividing(hdu 6060)

RXD and dividing(hdu 6060)

RXD and dividing

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


 

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

Source

【題意】給你一棵樹,將節點[2,n]最多分為k份,再將1節點加入到每一份,將每一份的節點連線起來,權值之和加入ans,求最大化ans。

思路:

每一個 節點與他父親節點之間的權值的貢獻就是他子樹分成的份數,那我們就最大化這個份

因為每個集合都包含1這個點,
因此對於每個點都至少有一條到1的路徑。可以從1開始DFS,
對於每個點u,它和父親的邊的貢獻最多可以是min(sz[x], k),因為可以把x的兒子結點分在不同的k個集合裡面,這些兒子結點都必須經過x和父親的邊才能到達1。
那麼對於每條邊都這樣做一遍。一個DFS可以求出答案。

#include<bits/stdc++.h>
using namespace std;
struct Edge{
    int v,w;
}temp;
vector<Edge>ve[1000005];
int ss[1000005];
int w[1000005];
void dfs(int u,int pre);
int main(){
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF){
        for(int i=1;i<=n;i++){
            ve[i].clear();
            ss[i]=0;
            w[i]=0;
        }

        for(int i=1;i<=n-1;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            temp.v=v;
            temp.w=w;
            ve[u].push_back(temp);
            temp.v=u;
            ve[v].push_back(temp);
        }
        dfs(1,-1);
        long long sum=0;
        for(int i=2;i<=n;i++)
        {
            sum+=(long long int)w[i]*min(ss[i],k);
        }
        printf("%lld\n",sum);
    }
    return 0;
}
void dfs(int u,int pre){
    ss[u]=1;
    int len=ve[u].size();
    for(int i=0;i<len;i++){
        int v=ve[u][i].v;
        if(v!=pre){
            w[v]=ve[u][i].w;
            dfs(v,u);
            ss[u]+=ss[v];
        }
    }
}