Dsa Exp 8 9 10
Dsa Exp 8 9 10
#include <iostream>
#include <vector>
using namespace std;
int main() {
int V, E;
cout << "Enter number of vertices: ";
cin >> V;
cout << "Enter number of edges: ";
cin >> E;
createGraph(adjMatrix, E);
displayGraph(adjMatrix);
calculateDegrees(adjMatrix);
return 0;
}
OUTPUT
CODE
#include <iostream>
#include <vector>
#include <queue>
queue<int> q;
q.push(root);
visited[root] = true;
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
q.push(neighbor);
visited[neighbor] = true;
visited[node] = true;
for (size_t i = 0; i < tree[node].size(); i++) {
if (!visited[neighbor]) {
int main() {
int V, E;
cin >> V;
cin >> E;
int u, v;
tree[u].push_back(v);
tree[v].push_back(u);
int root;
BFS(tree, root);
DFS_Start(tree, root);
return 0;
OUTPUT
CODE
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
class Edge {
public:
int u, v, weight;
};
class DisjointSet {
private:
public:
DisjointSet(int n) {
parent.resize(n);
rank.resize(n, 0);
parent[i] = i;
int find(int u) {
if (u != parent[u]) {
parent[u] = find(parent[u]);
}
return parent[u];
if (rootU != rootV) {
parent[rootV] = rootU;
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
};
// Kruskal's Algorithm
DisjointSet ds(V);
vector<Edge> mst;
if (ds.find(edge.u) != ds.find(edge.v)) {
mst.push_back(edge);
ds.unionSets(edge.u, edge.v);
// Prim's Algorithm
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
int start = 0;
pq.push(make_pair(0, start));
int mstCost = 0;
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (inMST[u]) continue;
inMST[u] = true;
mstCost += weight;
cout << "Vertex included: " << u << " with weight " << weight << endl;
int v = adjList[u][i].first;
int w = adjList[u][i].second;
if (!inMST[v]) {
pq.push(make_pair(w, v));
cout << "Total cost of MST: " << mstCost << endl;
}
int main() {
int V, E;
cin >> V;
cin >> E;
vector<Edge> edges;
int u, v, weight;
edges.push_back(Edge(u, v, weight));
adjList[u].push_back(make_pair(v, weight));
adjList[v].push_back(make_pair(u, weight));
kruskal(V, edges);
prim(V, adjList);
return 0;
}
OUTPUT