Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerEarth Maximum Spanning Tree problem solution

YASH PAL, 31 July 2024
In this HackerEarth Maximum Spanning Tree problem solution You are given a weighted graph with N vertices and M edges. Find the total weight of its maximum spanning tree.
HackerEarth Maximum Spanning Tree problem solution

HackerEarth Maximum Spanning Tree problem solution.

#include<bits/stdc++.h>

using namespace std;

int tests;
int n,m;
int a[1<<20],b[1<<20],c[1<<20];
vector<pair<int, int> > v;
int w[1<<20];
int ans;

int get(int x)
{
if (x==w[x])
return x;
return w[x]=get(w[x]);
}

void merge(int a,int b)
{
w[a]=b;
}

int main(){
ios_base::sync_with_stdio(0);

cin>>tests;
for (;tests;--tests)
{
cin>>n>>m;
v.clear();
for (int i=1;i<=m;i++)
{
cin>>a[i]>>b[i]>>c[i];
v.push_back(make_pair(c[i],i));
}
sort(v.begin(),v.end());
reverse(v.begin(),v.end());
for (int i=1;i<=n;i++)
w[i]=i;

ans=0;

for (int i=0;i<v.size();i++)
{
int id=v[i].second;
int q,w;
q=a[id];
w=b[id];
q=get(q);
w=get(w);
if (q!=w)
{
ans+=c[id];
merge(q,w);
}
}
cout<<ans<<endl;
}

return 0;}
coding problems solutions

Post navigation

Previous post
Next post

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes