I read about finding the Minimum Spanning Tree using kruskal’s Algorithm.I am trying the same algorithm to find Max. Spanning Tree.So, I made a vector of type<int,<int,int>> where first int here represents the weight of edge and 2nd and 3rd int are the vertices between which the edge is. After taking the input I sorted it in Descending order and then finally i greedily approached it by taking the maximum weight edged into the tree. To check that cycles are not being formed, I made a map vis which would map every visited node to one.
#include <bits/stdc++.h>
using namespace std;
map<int, int> vis;
int n, m;
vector<pair<int, pair<int, int>>> wts;
int mst()
{
int ans = 0,c=0;
for (int i = 0; i < m; i++)
{
if (vis[wts[i].second.first] && vis[wts[i].second.second])
continue;
vis[wts[i].second.first] = 1;
vis[wts[i].second.second] = 1;
ans += wts[i].first;
c++;
if(c>=n-1) break;//tree formation done
}
return ans;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
wts.push_back({c, {a, b}});
}
sort(wts.begin(), wts.end(), greater<pair<int, pair<int, int>>>());
cout << mst()<<endl;
}
I took the condition of a cycle being formed as when the vertices of the edge i am taking into consideration are already both visited.
Apparently it is not working. It is given W.A.
Where could it be going wrong?