Daa 56
Daa 56
#include<iostream>
#include<vector>
public:
graph(int size){
this->size=size;
adjlist.resize(size);
}
}
cout<<endl;
}
}
fi
void prims(int start){
vector<int>child(size,INT_MAX);
vector<int>parent(size,-1);
vector<bool>inmst(size,false);
child[start]=0;
while(!pq.empty()){
int u=pq.top().second;
pq.pop();
if(inmst[u])
continue;
inmst[u]=true;
for(auto [v,weight]:adjlist[u]){
if(!inmst[v]&&child[v]>weight){
child[v]=weight;
pq.push(make_pair(child[v],v));
parent[v]=u;
}
}}
for(int i=0;i<size;i++){
cout<<parent[i]<<"-"<<i<<" "<<child[i]<<endl;
}
}
void kruskal(){
};
};
int main(){
int V = 5;
graph g(V);
g.addEdge(0, 1, 2);
g.addEdge(0, 3, 6);
g.addEdge(1, 2, 3);
g.addEdge(1, 3, 8);
g.addEdge(1, 4, 5);
g.addEdge(2, 4, 7);
g.addEdge(3, 4, 9);
return 0;
OUTPUT:
PROGRAM 7
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <chrono>
#include <cstdlib>
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (inMST[u]) continue;
inMST[u] = true;
for (size_t i = 0; i < adj[u].size(); i++) {
int weight = adj[u][i]. rst, v = adj[u][i].second;
if (!inMST[v] && weight < key[v]) {
key[v] = weight;
pq.push(make_pair(weight, v));
parent[v] = u;
}
fi
}
}
}
struct Edge {
int u, v, weight;
};
class DSU {
vector<int> parent, rank;
public:
DSU(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; i++) parent[i] = i;
}
int nd(int x) { return parent[x] == x ? x : (parent[x] = nd(parent[x])); }
void unite(int x, int y) {
int rx = nd(x), ry = nd(y);
if (rx != ry) {
if (rank[rx] < rank[ry]) parent[rx] = ry;
else if (rank[rx] > rank[ry]) parent[ry] = rx;
else { parent[ry] = rx; rank[rx]++; }
}
}
};
int main() {
int n=5;
vector<pair<int,int> >adj[n];
vector<int> sizes;
sizes.push_back(10);
sizes.push_back(100);
sizes.push_back(1000);
sizes.push_back(10000);
sizes.push_back(50000);
sizes.push_back(100000);
sizes.push_back(200000);
start = high_resolution_clock::now();
kruskalMST(V, edges);
end = high_resolution_clock::now();
kruskalTimes.push_back(duration_cast<milliseconds>(end -
start).count());
cout << "V=" << V << " | Prim: " << primTimes.back() << "ms | Kruskal:
" << kruskalTimes.back() << "ms\n";
}
return 0;
}
OUTPUT:
prim's kruskal's
700
525
350
175
0
10 100 1000 10000 50000 100000 200000
V PRIM'S KRUSKAL'S
10 0 0
100 0 0
1000 3 0
10000 25 5
50000 131 29
100000 314 58