1. 程式人生 > >2017 Multi-University Training Contest - Team 3

2017 Multi-University Training Contest - Team 3

E - RXD and dividing

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 Si⋂Sj=∅Si⋂Sj=∅. 
Then he calulates res=∑ki=1f({1}⋃Si)res=∑i=1kf({1}⋃Si). 
He wants to maximize the resres. 
1≤k≤n≤1061≤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 SSconnected, and you need to minimize the sum of the cost of these edges. f(S)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,kn,k, which means the number of the tree nodes , and kk means the number of parts. 
The next n−1n−1 lines consists of 2 integers, a,b,ca,b,c, means a tree edge (a,b)(a,b) with cost cc. 
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≤100n≤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

思路:有點構造的感覺 ,就是取一種萬能的構造方法!從點1,到所有點遍歷一遍就可以了,維護一下  子樹節點的個數就可以,再就是k和節點個數關係不同是,轉化一下思維就可以,感覺比較有意思的一個題,當初沒有想出來,也是怪可惜的。。。

大佬寫的很詳細:傳送門

我的程式碼:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
struct AA
{
    ll v,w,next;
}pos[20000010];
ll f[10000010],num,z;
ll ans,dis[10000010],k;

ll n,u,v,w;
void dfs(ll rt,ll x,ll faa)
{
    dis[rt]=1;//cout<<rt<<" "<<x<<endl;
    for(int i=f[rt];i!=-1;i=pos[i].next)
    {
        ll vv=pos[i].v;
        if(vv==faa) continue;
        dfs(vv,pos[i].w,rt);
        dis[rt]+=dis[vv];
    }
    ans+=x*min(k,dis[rt]);
   // cout<<ans<<" "<<x<<" "<<dis[rt]<<" "<<k<<endl;
    return;
}
int main()
{
    while(scanf("%lld%lld",&n,&k)!=EOF)
    {
        num=0;
        for(int i=0;i<n+4;i++)
        {
            f[i]=-1;dis[i]=0;
        }
        for(int i=1;i<n;i++)
        {
            scanf("%lld%lld%lld",&u,&v,&w);
            pos[++num].v=v;
            pos[num].next=f[u];
            pos[num].w=w;
            f[u]=num;

            pos[++num].v=u;
            pos[num].next=f[v];
            pos[num].w=w;
            f[v]=num;
        }
        ans=0;
        dfs(1,0,-11);
        printf("%lld\n",ans);
    }
}
/*
5 4
1 2 3
2 3 4
2 4 5
2 5 6
5 2
1 2 3
2 3 4
2 4 5
2 5 6
*/