#include<bits/stdc++.h>
#define s source
#define w weight
#define k key
#define p pair<int, int>
#define N 100000
using namespace std;
int node, edge;
void make_edge(vector<p>adj[], int u, int v, int w)
{
adj[u].push_back(p(v, w));
adj[v].push_back(p(u, w));
}
void mst(vector<p>adj[], int vertex)
{
priority_queue<p, vector<p>, greater<p>> pq;
int s = 0;
vector<int> k(vertex, N);
vector<int> parent(vertex, -1);
vector<bool> include(vertex, false);
pq.push(p(0, s));
k[s] = 0; // each node value
while(!pq.empty())
{
int node = pq.top().second;
pq.pop();
if(include[node] == true)
continue;
include[node] = true;
for(p x : adj[node])
{
int n2 = x.first;
int w = x.second;
if(include[n2] == false && k[n2] > w)
{
k[n2] = w;
pq.push(p(w, n2));
parent[n2] = node;
}
}
}
for(int i=1;i<vertex;i++)
cout << parent[i] << " Connect with " << i << "\n";
}
int main()
{
cout << "Enter Node And Edge Number :: ";
cin >> node >> edge;
vector<p>adj[node];
int node1, node2, weight;
cout << "\nEnter Two Nodes and Weight :: \n";
for(int i=1;i<=edge;i++)
{
cin >> node1 >> node2 >> weight;
make_edge(adj, node1, node2, weight);
}
cout << "\n";
mst(adj, node);
return 0;
}
#define s source
#define w weight
#define k key
#define p pair<int, int>
#define N 100000
using namespace std;
int node, edge;
void make_edge(vector<p>adj[], int u, int v, int w)
{
adj[u].push_back(p(v, w));
adj[v].push_back(p(u, w));
}
void mst(vector<p>adj[], int vertex)
{
priority_queue<p, vector<p>, greater<p>> pq;
int s = 0;
vector<int> k(vertex, N);
vector<int> parent(vertex, -1);
vector<bool> include(vertex, false);
pq.push(p(0, s));
k[s] = 0; // each node value
while(!pq.empty())
{
int node = pq.top().second;
pq.pop();
if(include[node] == true)
continue;
include[node] = true;
for(p x : adj[node])
{
int n2 = x.first;
int w = x.second;
if(include[n2] == false && k[n2] > w)
{
k[n2] = w;
pq.push(p(w, n2));
parent[n2] = node;
}
}
}
for(int i=1;i<vertex;i++)
cout << parent[i] << " Connect with " << i << "\n";
}
int main()
{
cout << "Enter Node And Edge Number :: ";
cin >> node >> edge;
vector<p>adj[node];
int node1, node2, weight;
cout << "\nEnter Two Nodes and Weight :: \n";
for(int i=1;i<=edge;i++)
{
cin >> node1 >> node2 >> weight;
make_edge(adj, node1, node2, weight);
}
cout << "\n";
mst(adj, node);
return 0;
}
Comments
Post a Comment