https://codeforces.com/contest/1095/problem/F
题意
给定n个点,每个点都有权值wt[i],点u和点v建一条边的代价是wt[u]+wt[v]。有m条特殊边其权重直接为w,可选可不选。求联通n个点所需的最小代价。
思路
想复杂了,n^2建图显然是不可能的。不考虑特殊边的情况下,必然是权重最小的点与其他所有点建立n-1条边,然后再加入m条特殊边,跑一边Kruskal即可。
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl "\n"
typedef long long ll;
typedef pair<int,int> piir;
const int maxn = 2e5+5;
const ll INF = 1e18;
int n,m,fa[maxn],tot;
ll mn,wt[maxn];
struct node{
int u,v;
ll w;
}e[maxn*2];
void init(){
tot=0;
for(int i=0;i<=n;i++){
fa[i]=i;
}
}
void add(int u,int v,ll w){
e[tot].u=u;
e[tot].v=v;
e[tot].w=w;
tot++;
}
bool cmp(node a,node b){
return a.w < b.w;
}
int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
void MST(){
ll ans = 0,cnt=0;
m+=(n-1);
sort(e,e+m,cmp);
for(int i=0;i<m;i++){
int fx=find(e[i].u),fy=find(e[i].v);
if(fx!=fy){
ans+=e[i].w;
fa[fx]=fy;
cnt++;
}
if(cnt==n-1)break;
}
cout<<ans<<endl;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
IOS;
cin>>n>>m;
init();
ll minv=INF,minid=0;
for(int i=1;i<=n;i++){
cin>>wt[i];
if(minv>wt[i]) minv=wt[i],minid=i;
}
for(int u,v,i=1;i<=m;i++){
ll w;
cin>>u>>v>>w;
add(u,v,w);
}
for(int i=1;i<=n;i++){
if(i==minid) continue;
add(minid,i,minv+wt[i]);
}
MST();
return 0;
}