2017多校3-5 RXD and dividing
思维题,dfs
题意
给一棵树,1为根。将2~n划分成不同的集合,并将1加入每个集合。使得每个集合构成的最小斯坦纳树的和最大。
思路
把1看成整棵树的根. 问题相当于把 2∼n 每个点一个[1, k]的标号. 然后根据最小斯坦纳树的定义, (x,fax) 这条边的贡献是 x 子树内不同标号的个数目 difi . 那么显然有 difi≤min(k,szi) , szi 表示子树大小. 可以通过构造让所有 difi 都取到最大值. 所以答案就是 ∑nx=2w[x][fax]∗min(szx,k) 。时间复杂度 O(n) 。
代码
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <iomanip>
using namespace std;
const int MAXN=1100007;
typedef long long LL;
struct Edge
{
int to;
LL co;
Edge() {}
Edge(int _a, LL _b) { to=_a, co=_b; }
};
vector<Edge> G[MAXN];
LL res=0;
int dfs(int u,int fa,int k,int cos)
{
int son=1;
for(int i=0;i<G[u].size();i++)
{
int to=G[u][i].to,cos=G[u][i].co;
if(to==fa) continue;
son+=dfs(to, u, k, cos);
}
int tmp=min(son, k);
res+=(LL)tmp*cos;
return son;
}
int main()
{
int n, K;
while(scanf("%d%d", &n, &K)==2)
{
for(int i=1;i<=n;i++)
G[i].clear();
for(int i=1;i<n;i++)
{
int a, b;
LL c;
scanf("%d%d%lld", &a, &b, &c);
G[a].push_back(Edge(b, c));
G[b].push_back(Edge(a, c));
}
res=0;
dfs(1, -1, K, 0);
printf("%lld\n", res);
}
//system("pause");
return 0;
}