首先建出 kruskal 重构树。
房屋到一个服务器的代价就是两点在重构树上的 LCA 所代表的边的边权。
然后我们观察一下,对于一个子树而言,假若子树中存在至少一个服务器,那么子树内的所有点与这个服务器匹配,代价为子树根的权值,是优于与子树外任意服务器匹配的,因为重构树上一个点的权值小于等于其所有祖先的权值。
因此一个子树对子树外而言只有两种状态,子树内存在至少一台服务器使得子树内所有需要联网的房屋全部满足要求,或者子树内一台服务器都不存在。
因此设计状态 表示子树 内有 台服务器时子树 内需要联网的房屋的最小花费之和,再令 表示 子树内需要联网的房屋数量,有 。
这个形式有点丑,但是不妨令 ,那么你发现 就是由 与 先做闵可夫斯基和再将 增加一个非负数得到。
dp 的边界条件是 ,此时 是凸的,因此在经过上述合并操作后依然是凸的,所以直接用可并堆维护差分数组即可做到 。
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 2e5+114;
int ls[maxn<<1],rs[maxn<<1];
int w[maxn<<1];
int fa[maxn<<1];
int found(int u){
return fa[u]=(fa[u]==u?u:found(fa[u]));
}
int n,m,p,tot;
pair<int,pair<int,int> > e[maxn];
const int inf = 1e9+114;
int root[maxn<<1];
int g[maxn<<1];
struct node{
int v,ls,rs,dist;
node(){
v=ls=rs=dist=0;
}
}tr[maxn];//大根堆
int cnt;
void pushup(int cur){
if(tr[tr[cur].ls].dist<tr[tr[cur].rs].dist) swap(tr[cur].ls,tr[cur].rs);
tr[cur].dist=tr[tr[cur].rs].dist+1;
}
int merge(int a,int b){
if(a==0||b==0) return a+b;
if(tr[a].v>tr[b].v){
tr[a].rs=merge(tr[a].rs,b);
pushup(a);
return a;
}
tr[b].rs=merge(tr[b].rs,a);
pushup(b);
return b;
}
int sz[maxn<<1];
void dp(int u,int fa){
if(u<=n){
g[u]=sz[u]*w[fa];
cnt++;
tr[cnt].v=g[u];
root[u]=cnt;
return ;
}
dp(ls[u],u),dp(rs[u],u);
root[u]=merge(root[ls[u]],root[rs[u]]);
g[u]=g[ls[u]]+g[rs[u]];
sz[u]=sz[ls[u]]+sz[rs[u]];
tr[root[u]].v+=sz[u]*w[fa]-g[u];
g[u]=sz[u]*w[fa];
return ;
}
void work(){
cin>>n>>m>>p;
tot=n;
for(int i=1;i<=p;i++){
int x;
cin>>x;
sz[x]=1;
}
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++) cin>>e[i].second.first>>e[i].second.second>>e[i].first;
sort(e+1,e+m+1);
for(int i=1;i<=m;i++){
int u=found(e[i].second.first),v=found(e[i].second.second);
if(u!=v){
tot++;
ls[tot]=u,rs[tot]=v;
fa[tot]=fa[u]=fa[v]=tot;
w[tot]=e[i].first;
}
}
w[0]=inf;
dp(tot,0);
for(int i=1;i<=n;i++){
g[tot]-=tr[root[tot]].v;
root[tot]=merge(tr[root[tot]].ls,tr[root[tot]].rs);
cout<<g[tot]<<' ';
}
cout<<'\n';
for(int i=1;i<=cnt;i++) tr[i]=node();
for(int i=1;i<=tot;i++) sz[i]=g[i]=root[i]=ls[i]=rs[i]=w[i]=fa[i]=0;
cnt=tot=0;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--) work();
return 0;
}