道路修复
思路: 国之诸城震后道毁欲复连通费求至省原有城邑n旧道m乡镇k枚举乡镇取舍之状择其乡镇纳其造费合旧道与新筑之路求最小生成树计总费取其极微者乃为答案
翻译: 枚举k个乡镇的选择子集,对每个子集,合并原道路+选中乡镇连城市的边,求最小生成树,总费用为改造选中乡镇费用+边权和,取最小值。
代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int f[1000010],b[20],vis[20];
struct db{
int x,y,w;
}ori[1000010],a[1000010];
bool cmp(db a,db b){
return a.w<b.w;
}
int find(int x){
if(x==f[x]){
return x;
}
f[x]=find(f[x]);
return f[x];
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m,k;
cin>>n>>m>>k;
for(int i=1; i<=m; i++){
int x,y,w;
cin>>x>>y>>w;
ori[i].x=x;
ori[i].y=y;
ori[i].w=w;
}
sort(ori+1,ori+m+1,cmp);
for(int i=1; i<=n; i++){
f[i]=i;
}
int cnt=0;
for(int i=1; i<=m; i++){
int x=find(ori[i].x);
int y=find(ori[i].y);
if(x!=y){
f[y]=x;
a[++cnt]=ori[i];
if(cnt==n-1){
break;
}
}
}
for(int i=1; i<=k; i++){
cin>>b[i];
for(int j=1; j<=n; j++){
int w;
cin>>w;
a[++cnt].x=j;
a[cnt].y=n+i;
a[cnt].w=w;
}
}
sort(a+1,a+cnt+1,cmp);
int ans=1e18;
for(int stat=0; stat<(1<<k); stat++){
int now=0;
int num=0;
for(int i=1; i<=k; i++){
if((stat>>(i-1))&1){
++num,vis[i]=1;
now+=b[i];
}else{
vis[i]=0;
}
}
for(int i=1; i<=n+k; i++){
f[i]=i;
}
int need=n+num-1;
for(int i=1; i<=cnt; i++){
int u=a[i].x,v=a[i].y;
if(v>n && !vis[v-n]){
continue;
}
int x=find(u),y=find(v);
if(x!=y){
f[y]=x;
now+=a[i].w;
if(!(--need)){
break;
}
}
}
if(!need){
ans=min(ans,now);
}
}
cout<<ans<<"\n";
return 0;
}