Codeforces 1095F Make It Connected(最小生成树)

题目链接:Make It Connected

题意:给定一张$n$个顶点(每个顶点有权值$a_i$)的无向图,和已连接的拥有边权$w_i$的$m$条边,顶点u和顶点v直接如果新建边,边权为$a_u+a_v$,求图连通的最小边权和。

题解:假定连接三个顶点$u$,$v$,$p$,顶点权值按$a_u,a_v,a_p$从小到大排序。连通三个顶点的最小边权和为$(a_u+a_v)+(a_u+a_p)$,即最小权值的顶点连接其他顶点时,花费最小,推广到n个顶点也相同。因此该题就是m+n-1条边求小最小生成树即可。

 1 #include <set>
 2 #include <map>
 3 #include <queue>
 4 #include <deque>
 5 #include <stack>
 6 #include <cmath>
 7 #include <cstdio>
 8 #include <vector>
 9 #include <string>
10 #include <cstring>
11 #include <fstream>
12 #include <iostream>
13 #include <algorithm>
14 using namespace std;
15 
16 #define eps 1e-8
17 #define pb push_back
18 #define PI acos(-1.0)
19 #define INF 0x3f3f3f3f
20 #define clr(a,b) memset(a,b,sizeof(a)
21 #define bugc(_) cerr << (#_) << " = " << (_) << endl
22 #define FAST_IO ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
23 
24 const int N=2e5+10;
25 typedef long long ll;
26 typedef unsigned long long ull;
27 struct node{
28     int id;
29     ll a;
30 }p[N];
31 
32 struct NODE{
33     int u,v;
34     ll cost;
35 }pi[4*N];
36 
37 bool cmp1(node x,node y){
38     return x.a<y.a;
39 }
40 
41 bool cmp2(NODE x,NODE y){
42     return x.cost<y.cost;
43 }
44 
45 int fa[4*N];
46 int fi(int x){
47     return fa[x]==x?x:fa[x]=fi(fa[x]);
48 }
49 
50 int main(){
51     FAST_IO;
52     int n,m;
53     cin>>n>>m;
54     for(int i=1;i<=n;i++){
55         cin>>p[i].a;
56         p[i].id=i;
57     }
58     sort(p+1,p+1+n,cmp1);
59     //n-1
60     for(int i=2;i<=n;i++){
61         pi[i-1+m].u=p[1].id;
62         pi[i-1+m].v=p[i].id;
63         pi[i-1+m].cost=p[1].a+p[i].a;
64     }
65     for(int i=1;i<=m;i++){
66         cin>>pi[i].u>>pi[i].v>>pi[i].cost;
67     }
68     sort(pi+1,pi+1+m+n-1,cmp2);
69     ll ans=0;
70     for(int i=1;i<=4*N;i++) fa[i]=i;
71     for(int i=1;i<=m+n-1;i++){
72         int x=pi[i].u;
73         int y=pi[i].v;
74         int fx=fi(x),fy=fi(y);
75         if(fx!=fy){
76             fa[fx]=fy;
77             ans+=pi[i].cost;
78         }
79     }
80     cout<<ans<<endl;
81     return 0;
82 }
View Code

 

posted @ 2018-12-30 10:28  pavtlly  阅读(782)  评论(0编辑  收藏  举报