Chủ Nhật, 6 tháng 1, 2019

Codeforces Round #529 (Div.3)- Bài 6

Bài 6: You are given an undirected graph consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is $a_i$. 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 $x$ and $y$ is $a_x+a_y$ coins. There are also $m$ special offers, each of them is denoted by three numbers $x,y$ and $w$, and means that you can add an edge connecting vertices $x$ and $y$ and pay $w$ coins for it. You don't have to use special offers; if there is a pair of vertices $x$ and $y$ that has a special offer associated with it, you still may connect these two vertices paying $a_x+a_y$ coins for it.

What is 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 ti this graph.
Input
The first line contains two integers $n$ and $m(1\le n\le 2.10^5,0\le m\le 2.10^5)$- the number of vertices in the graph and the number of speacial offers, respectively.

The second line contains $n$ integers $a_1,a_2,...,a_n(1\le a_i\le 10^{12})$- the numbers written on the vertices.
Then $m$ lines follow, each containing three integers $x,y$ and $w(1\le x,y\le n,1\le w\le 10^{12},x\ne y)$ denoting a speacial offer: you may add an edge connecting vertex $x$ and vectex $y$, and this edge will cost $w$ coins.
Input
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
Solution:
#include<bits/stdc++.h>
#define int long long
using namespace std;const int N=2e5+7;
struct data{int u,v,w;}s[N*2];int n,m,i,j,k,a[N],fa[N],ans,cnt;
bool operator<(data a,data b){return a.w<b.w;}
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
int32_t main(){
    for(k=1e13,cin>>n>>m,i=1;i<=n;++i){
        cin>>a[i];fa[i]=i;
        if(a[i]<k)k=a[i],j=i;
    }
    for(i=1;i<=n;++i)if(i!=j)s[++cnt]=data{i,j,a[i]+k};
    for(;m--;){cin>>i>>j>>k;s[++cnt]=data{i,j,k};}
    for(sort(s+1,s+cnt+1),i=1;i<=cnt;++i)if((j=find(s[i].u))!=(k=find(s[i].v)))fa[j]=k,ans+=s[i].w;
    cout<<ans<<endl;
}

Không có nhận xét nào:

Đăng nhận xét

Bài G - Educatioal Round 62

Đề bài: Bạn được cho 1 đồ thị vô hướng đặc biệt. Nó bao gồm $2n$ đỉnh được đánh số từ 1 đến 2n. Dưới đây là một số đặc tính của đồ thị: + ...