1. 程式人生 > >Codeforces 1095F Make It Connected(最小生成樹)

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