19BCS099 - Assignment On Prims and Kruskal Algorithm
19BCS099 - Assignment On Prims and Kruskal Algorithm
Ans :
The cost of the spanning tree is the sum of the weights of all the edges in the tree. There can be
many spanning trees. Minimum spanning tree is the spanning tree where the cost is minimum
among all the spanning trees. There also can be many minimum spanning trees.
Minimum spanning tree has direct application in the design of networks. It is used in algorithms
approximating the travelling salesman problem, multi-terminal minimum cut problem and
minimum-cost weighted perfect matching. Other practical applications are:
1. Cluster Analysis
2. Handwriting recognition
3. Image segmentation
2. Write Prim’s and Kruskal’s algorithm to solve minimum spanning tree problems.
Ans:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
void initialize()
{
for(int i = 0;i < MAX;++i)
id[i] = i;
}
int root(int x)
{
while(id[x] != x)
{
id[x] = id[id[x]];
x = id[x];
}
return x;
}
int main()
{
int x, y;
long long weight, cost, minimumCost;
initialize();
cin >> nodes >> edges;
for(int i = 0;i < edges;++i)
{
cin >> x >> y >> weight;
p[i] = make_pair(weight, make_pair(x, y));
}
sort(p, p + edges);
minimumCost = kruskal(p);
cout << minimumCost << endl;
return 0;
}
#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <utility>
int main()
{
int nodes, edges, x, y;
long long weight, minimumCost;
cin >> nodes >> edges;
for(int i = 0;i < edges;++i)
{
cin >> x >> y >> weight;
adj[x].push_back(make_pair(weight, y));
adj[y].push_back(make_pair(weight, x));
}
// Selecting 1 as the starting node
minimumCost = prim(1);
cout << minimumCost << endl;
return 0;
}
Ans:
In Kruskal’s algorithm, most time consuming operation is sorting because the total complexity of
the Disjoint-Set operations will be O(ElogV), which is the overall Time Complexity of the
algorithm.
Prim’s algorithms complexity Analysis:
The time complexity of the Prim’s Algorithm is O((V+E)logV) because each vertex is inserted in
the priority queue only once and insertion in priority queue takes logarithmic time.
4. The number of distinct minimum spanning trees for the weighted graph below
is ____
Ans:
The number of distinct minimum spanning trees for the weighted graph below is 6
Ans :
(v1) _ (v2)
|
(v3)
Total weight= 3 + 4 = 7
We can observe from the above examples that when we add kth nodes,
the weight of the spanning tree increases by 2k-2. Let T(n) be the weight
of the minimum spanning tree. T(n) can be written as