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;
}