Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // NgJaBach: Forever Meadow <3
- #include<bits/stdc++.h>
- using namespace std;
- mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
- typedef long long int ll;
- typedef unsigned long long ull;
- #define pb push_back
- #define pob pop_back
- #define mp make_pair
- #define upb upper_bound
- #define lwb lower_bound
- #define bend(a) a.begin(),a.end()
- #define rev(x) reverse(bend(x))
- #define mset(a) memset(a, 0, sizeof(a))
- #define fi first
- #define se second
- #define gcd __gcd
- #define getl(s) getline(cin, s);
- #define setpre(x) fixed << setprecision(x)
- #define endl '\n'
- const int N=100050,M=1000000007;
- const ll INF=1e18+7;
- int cha[N],cha_size[N];
- int find_cha(int u){
- if(cha[u]==u) return u;
- return cha[u]=find_cha(cha[u]);
- }
- bool European_Union(int u,int v){
- int a,b;
- a=find_cha(u); b=find_cha(v);
- if(a==b) return false;
- if(cha_size[a]<cha_size[b]) swap(a,b);
- cha[b]=a;
- cha_size[a]+=cha_size[b];
- return true;
- }
- int main(){
- ios_base::sync_with_stdio(NULL); cin.tie(nullptr); cout.tie(nullptr);
- freopen("MST.inp","r",stdin);
- freopen("MST.out","w",stdout);
- int n,m,x,y,cnt;
- ll z,sum=0;
- vector<pair<ll,pair<int,int> > >gay;
- cin>>n>>m;
- cnt=n;
- for(int i=1;i<=n;++i){
- cha[i]=i;
- cha_size[i]=1;
- }
- for(int i=0;i<m;++i){
- cin>>x>>y>>z;
- gay.pb({z,{x,y}});
- }
- sort(bend(gay));
- for(int i=0;i<m;++i){
- x=gay[i].se.fi; y=gay[i].se.se; z=gay[i].fi;
- if(European_Union(x,y)){
- sum+=z;
- --cnt;
- }
- }
- if(cnt>1) sum=-1;
- cout<<sum;
- return 0;
- }
- /*
- ==================================+
- INPUT: |
- ------------------------------ |
- ------------------------------ |
- ==================================+
- OUTPUT: |
- ------------------------------ |
- ------------------------------ |
- ==================================+
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement