/***
Md. Namzul Hasan
Shahjalal University of Science & Technology,sylhet.
hasan08sust@gmail.com
***/
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
typedef int in ;
typedef unsigned long long ull ;
const double pi = 2*acos(0) ;
#define maxi 40000
#define pf printf
#define sc scanf
#define pb push_back
#define MEM(x,y) (memset((x),(y),sizeof(x)))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define load(array,size) for(int i=0 ; i<size ; i++) cin>>array[i] ;
#define new_line pf("\n")
#define mx 2147483647
struct edge
{
int u,v,w ;
bool operator < (const edge& p ) const
{
return w< p.w ;
}
};
int pr[mx] ;
vector<edge> e ;
int find_dis(int r)
{
return (pr[r]==r ? r : find_dis(pr[r])) ;
}
int mst(int n)
{
sort(e.begin(), e.end()) ;
for(int i=1 ; i<=n ; i++)
pr[i] = i ;
int cnt =0 , s =0 ;
for(int i=0 ; i<e.size() ; i++)
{
int u = find_dis(e[i].u) ;
int v = find_dis(e[i].v) ;
if(u!=v)
{
pr[u] = v ;
cnt++ ;
s+=e[i].w ;
if(cnt==n-1)
break ;
}
}
return s ;
}
int main()
{
int n , m ;
cin>>n>>m ;
for(int i=1; i<=m ; i++)
{
int u ,v ,w ;
cin>>u>>v>>w ;
edge get ;
get.u = u ;
get.v = v ;
get.w = w ;
e.pb(get) ;
}
cout<<mst(n)<<endl ;
return 0;
}
Md. Namzul Hasan
Shahjalal University of Science & Technology,sylhet.
hasan08sust@gmail.com
***/
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
typedef int in ;
typedef unsigned long long ull ;
const double pi = 2*acos(0) ;
#define maxi 40000
#define pf printf
#define sc scanf
#define pb push_back
#define MEM(x,y) (memset((x),(y),sizeof(x)))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define load(array,size) for(int i=0 ; i<size ; i++) cin>>array[i] ;
#define new_line pf("\n")
#define mx 2147483647
struct edge
{
int u,v,w ;
bool operator < (const edge& p ) const
{
return w< p.w ;
}
};
int pr[mx] ;
vector<edge> e ;
int find_dis(int r)
{
return (pr[r]==r ? r : find_dis(pr[r])) ;
}
int mst(int n)
{
sort(e.begin(), e.end()) ;
for(int i=1 ; i<=n ; i++)
pr[i] = i ;
int cnt =0 , s =0 ;
for(int i=0 ; i<e.size() ; i++)
{
int u = find_dis(e[i].u) ;
int v = find_dis(e[i].v) ;
if(u!=v)
{
pr[u] = v ;
cnt++ ;
s+=e[i].w ;
if(cnt==n-1)
break ;
}
}
return s ;
}
int main()
{
int n , m ;
cin>>n>>m ;
for(int i=1; i<=m ; i++)
{
int u ,v ,w ;
cin>>u>>v>>w ;
edge get ;
get.u = u ;
get.v = v ;
get.w = w ;
e.pb(get) ;
}
cout<<mst(n)<<endl ;
return 0;
}
No comments:
Post a Comment