F. Make It Connected
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an undirected graph consisting of nn vertices. A number is written on each vertex; the number on vertex ii is aiai . Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices xx and yy is ax+ayax+ay coins. There are also mm special offers, each of them is denoted by three numbers xx , yy and ww , and means that you can add an edge connecting vertices xx and yy and pay ww coins for it. You don't have to use special offers: if there is a pair of vertices xx and yy that has a special offer associated with it, you still may connect these two vertices paying ax+ayax+ay coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers nn and mm (1≤n≤2⋅1051≤n≤2⋅105 , 0≤m≤2⋅1050≤m≤2⋅105 ) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10121≤ai≤1012 ) — the numbers written on the vertices.
Then mm lines follow, each containing three integers xx , yy and ww (1≤x,y≤n1≤x,y≤n , 1≤w≤10121≤w≤1012 , x≠yx≠y ) denoting a special offer: you may add an edge connecting vertex xx and vertex yy , and this edge will cost ww coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
Copy
3 2
1 3 3
2 3 5
2 1 1
Output
Copy
5
Input
Copy
4 0
1 3 3 7
Output
Copy
16
Input
Copy
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
Copy
18
Note
In the first example it is possible to connect 11 to 22 using special offer 22 , and then 11 to 33 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
从value最小的点连向其他所有点
#include <bits/stdc++.h>
using namespace std;
int n,m;
#define maxn 400005
#define ll long long
#define inf 1ll<<62
struct edge
{
int from,to;
ll weight;
}e[maxn];
int parent[maxn];
ll value[maxn];
bool cmp(edge a,edge b)
{
return a.weight<b.weight;
}
int find(int x)
{
return parent[x]==x?x:parent[x]=find(parent[x]);
}
int main()
{
int cnt=0;
ll ans=0;
cin>>n>>m;
ll mini=inf;
int idx;
for(int i=1;i<=n;i++)
{
parent[i]=i;
cin>>value[i];
if(mini>value[i])
{
mini=value[i];
idx=i;
}
}
for(int i=0;i<m;i++)
{
int a,b;
ll w;
cin>>a>>b>>w;
w=min(w,value[b]+value[a]);
e[cnt].from=a;
e[cnt].to=b;
e[cnt].weight=w;
cnt++;
}
for(int i=1;i<=n;i++)
{
if(i!=idx)
{
e[cnt].from=idx;
e[cnt].to=i;
e[cnt].weight=value[idx]+value[i];
cnt++;
}
}
sort(e,e+cnt,cmp);
for(int i=0;i<cnt;i++)
{
int x=find(e[i].from);
int y=find(e[i].to);
if(x!=y)
{
ans+=e[i].weight;
parent[y]=x;
}
}
cout<<ans<<endl;
//system("pause");
return 0;
}