Prim's (MST) : Special Subtree

Given a graph that consists of several edges connecting its nodes, find a subgraph of the given graph with the following properties:

  • The subgraph contains all the nodes present in the original graph.
  • The subgraph is of minimum overall weight (sum of all edges) among all such subgraphs.
  • It is also required that there is exactly one, exclusive path between any two nodes of the subgraph.

One specific node  is fixed as the starting point of finding the subgraph using Prims Algorithm
Find the total weight or the sum of all edges in the subgraph.


Example:
Input:  n=5,m=6,s=1,edges={{0,1,3},{0,2,4},{3,1,6},{4,1,2},{1,2,5},{2,4,7}}
Output: 15

Approach

C++

#include <bits/stdc++.h>
using namespace std;
#define INF 1000000000
struct Edge
{
    int tocost = INF;
};
int main()
{

    int n = 5m = 6s = 1;
    vector<list<Edge>> arr(nlist<Edge>());
    set<pair<intint>> left;
    set<intadd;
    vector<Edgemst;
    vector<intdist(n + 1INT_MAX);
    arr[0].push_back(Edge{13});
    arr[1].push_back(Edge{03});

    arr[0].push_back(Edge{24});
    arr[2].push_back(Edge{04});

    arr[3].push_back(Edge{16});
    arr[1].push_back(Edge{36});

    arr[4].push_back(Edge{12});
    arr[1].push_back(Edge{42});

    arr[1].push_back(Edge{25});
    arr[2].push_back(Edge{15});

    arr[2].push_back(Edge{47});
    arr[4].push_back(Edge{27});

    s--;
    dist[s] = 0;
    for (int i = 0i < ni++)
    {
        left.insert({dist[i]i});
    }
    int ans = 0;
    while (!left.empty())
    {
        int curr = left.begin()->second;
        ans += dist[curr];
        add.insert(curr);
        left.erase(left.begin());
        for (auto &edge : arr[curr])
        {
            if (add.count(edge.to) == 1)
                continue;
            int curr_min = dist[edge.to];
            if (edge.cost < curr_min)
            {
                left.erase({curr_minedge.to});
                dist[edge.to] = edge.cost;
                left.insert({dist[edge.to]edge.to});
            }
        }
    }
    cout << ans << "\n";
    return 0;
}


No comments:

Post a Comment