You are on page 1of 4

Assignment

Vinayak Sahni
20105125
ECE

Kruskal's algorithm
#include <bits/stdc++.h>
#define li long long
int using namespace
std;

class Edge{
public:
li start;
li destination;
li weight;
};

bool cmp(const Edge e1, const Edge


e2); li getparent(li* parent, li
index);

void kruskalAlgorithm(Edge* edges,li v,li e){


sort(edges,edges+e,cmp);
Edge* mst = new Edge[v-
1]; li* parent = new
li[v]; for(li i = 0;i <
v;i++){
parent[i] = i;
}
li count =
0; li i = 0;
while(count < v-1){
li p1 = getparent(parent,edges[i].start);
li p2 = getparent(parent,edges[i].destination);
if(p1 != p2){
mst[count] = edges[i];
count++;
parent[p1] = p2;
}
i++;
}
for(li i = 0;i < v-1;i++)
{ Edge edge = mst[i];
if(edge.start > edge.destination){
}else{
cout << edge.start << " " << edge.destination << " " << edge.weight << endl;
}
}
}

signed main() { li v,e;


cin >> v >> e;
Edge* edges = new Edge[e]; for(li i = 0;i < e;i++){
li start,weight,destination;
cin >> start >> destination >> weight; edges[i].start = start; edges[i].destination = desti
}
cout << "" << endl; cout << "OUTPUT:" << endl; kruskalAlgorithm(edges,v,e);
}

bool cmp(const Edge e1, const Edge e2){ return e1.weight < e2.weight;
}
li getparent(li* parent, li index){ while(parent[index] != index){
index = parent[index];
}
return index;
}

OUTPUT:
Prim’s Algorithm
#include <bits/stdc++.h>
#define li long long
int using namespace
std;

li findMinVertex(li* weights, bool* visited, li n);

void prims(li** edges, li n);

signed main() {
li n;
li e;
cin >> n >> e;
li** edges = new li*[n];
for (li i = 0; i < n; i++) {
edges[i] = new li[n];
for (li j = 0; j < n; j++) {
edges[i][j] = 0;
}
}

for (li i = 0; i < e; i++) {


li f, s, weight;
cin >> f >> s >> weight;
edges[f][s] = weight;
edges[s][f] = weight;
}
cout << " " <<
endl; cout << "OUTPUT:" << endl;
prims(edges, n);

for (li i = 0; i < n; i++) {


delete [] edges[i];
}
delete [] edges;
}

li findMinVertex(li* weights, bool* visited, li n){

li minVertex = -1;
for(li i = 0; i < n; i++){
if(!visited[i] && (minVertex == - 1 || weights[i]
< weights[minVertex])){
minVertex = i;
}
}
return minVertex;
}
void prims(li** edges, li n){

li* parent = new li[n]; li* weights = new li[n];


bool* visited = new bool[n];

for(li i = 0; i < n; i++){ visited[i] = false; weights[i] = INT_MAX;


}
parent[0] = -1;
weights[0] = 0;

for(li i = 0; i < n - 1; i++){


li minVertex = findMinVertex(weights, visited, n); visited[minVertex] = true;
for(li j = 0; j < n; j++){ if(edges[minVertex][j] != 0 && !visited[j]){
if(edges[minVertex][j] < weights[j]){ weights[j] = edges[minVertex][j]; parent[j] = minVer
}
}
}
}

for(li i = 1; i < n; i++){ if(parent[i] < i){


cout << parent[i] << " " << i << " " << weights[i] << endl;
}else{
cout << i << " " << parent[i] << " " << weights[i] << endl;
}
}
}

You might also like