0% found this document useful (0 votes)
4 views28 pages

Name:Rohan

The document presents multiple problem statements related to algorithms and data structures, including sorting algorithms (Merge Sort and Quick Sort), finding Kth smallest/largest elements, and checking for common elements in arrays. It also covers graph-related problems such as checking for paths, bipartiteness, and cycle detection using DFS and BFS. Each problem is accompanied by source code implementations and expected outputs.

Uploaded by

git.sumitjoshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views28 pages

Name:Rohan

The document presents multiple problem statements related to algorithms and data structures, including sorting algorithms (Merge Sort and Quick Sort), finding Kth smallest/largest elements, and checking for common elements in arrays. It also covers graph-related problems such as checking for paths, bipartiteness, and cycle detection using DFS and BFS. Each problem is accompanied by source code implementations and expected outputs.

Uploaded by

git.sumitjoshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PROBLEM STATEMENT 1: Given an unsorted array of integers, design an algorithm and

implement it using a program to sort an array of elements by dividing the array into two
subarrays and combining these subarrays after sorting each one of them. Your program should
also find number of comparisons and inversions during sorting the array.

SOURCE CODE:
#include <iostream>
using namespace std;

int comparisons = 0, inversions = 0;

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1, n2 = right - mid;
int L[n1], R[n2];
for(int i = 0; i < n1; i++) L[i] = arr[left + i];
for(int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];

int i = 0, j = 0, k = left;
while(i < n1 && j < n2) {
comparisons++;
if(L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
inversions += (n1 - i);
}
}
while(i < n1) arr[k++] = L[i++];
while(j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int left, int right) {


if(left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while(T--) {
int n;
cout << "Enter size of array: ";
cin >> n;
int arr[n];
cout << "Enter array elements: ";
for(int i = 0; i < n; i++) cin >> arr[i];

comparisons = 0; inversions = 0;
mergeSort(arr, 0, n - 1);

for(int i = 0; i < n; i++) cout << arr[i] << " ";


Name:Rohan Section:L1 Roll No. 45
cout << "\nComparisons = " << comparisons << endl;
cout << "Inversions = " << inversions << endl;
}
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 2: Given an unsorted array of integers, design an algorithm
and implement it using a program to sort an array of elements by partitioning the array
into two subarrays based on a pivot element such that one of the sub array holds values
smaller than the pivot element while another sub array holds values greater than the
pivot element. Pivot element should be selected randomly from the array. Your
program should also find number of comparisons and swaps required for sorting the
array.

SOURCE CODE:
#include <iostream>
#include <cstdlib>
using namespace std;

int comparisons = 0, swaps = 0;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
swaps++;
}

int partition(int arr[], int low, int high) {


int randomIndex = low + (high - low) / 2;
swap(arr[randomIndex], arr[high]);

int pivot = arr[high];


int i = low - 1;
for(int j = low; j < high; j++) {
comparisons++;
if(arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[high]);
return i+1;
}

void quickSort(int arr[], int low, int high) {


if(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while(T--) {
int n;
cout << "Enter size of array: ";
cin >> n;
int arr[n];
Name:Rohan Section:L1 Roll No. 44
cout << "Enter array elements: ";
for(int i = 0; i < n; i++) cin >> arr[i];

comparisons = swaps = 0;
quickSort(arr, 0, n - 1);

for(int i = 0; i < n; i++) cout << arr[i] << " ";


cout << "\nComparisons = " << comparisons << endl;
cout << "Swaps = " << swaps << endl;
}
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 12: Given an unsorted array of integers, design an algorithm and
implement it using a program to find Kth smallest or largest element in the array. (Worst case
Time Complexity = O(n))

SOURCE CODE:

#include <iostream>
#include <cstdlib>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;
for(int j = low; j < high; j++) {
if(arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[high]);
return i + 1;
}

int quickSelect(int arr[], int low, int high, int k) {


if(low <= high) {
int pi = partition(arr, low, high);
if(pi == k) return arr[pi];
else if(pi > k) return quickSelect(arr, low, pi - 1, k);
else return quickSelect(arr, pi + 1, high, k);
}
return -1;
}

int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while(T--) {
int n, k;
cout << "Enter size of array: ";
cin >> n;
int arr[n];
cout << "Enter array elements: ";
for(int i = 0; i < n; i++) cin >> arr[i];

cout << "Enter element position to find (K): ";


cin >> k;

if(k > 0 && k <= n) {


int result = quickSelect(arr, 0, n - 1, k - 1);
cout << k << "th smallest element: " << result << endl;
Name:Rohan Section:L1 Roll No. 44
} else {
cout << "Invalid position!" << endl;
}
}
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 1: Given an unsorted array of alphabets containing duplicate
elements. Design an algorithm and implement it using a program to find which alphabet has
maximum number of occurrences and print it. (Time Complexity = O(n)) (Hint: Use counting
sort)

SOURCE CODE:
#include <iostream>
#include <vector>
using namespace std;

void findMaxOccurrence(vector<char>& arr, int n) {


int maxCount = 0;
char maxChar = '\0';
char minChar = arr[0], maxCharRange = arr[0];

// Find min and max character


for (int i = 1; i < n; i++) {
if (arr[i] < minChar) minChar = arr[i];
if (arr[i] > maxCharRange) maxCharRange = arr[i];
}

int range = maxCharRange - minChar + 1;


vector<int> count(range, 0);

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


count[arr[i] - minChar]++;
if (count[arr[i] - minChar] > maxCount) {
maxCount = count[arr[i] - minChar];
maxChar = arr[i];
}
}

if (maxCount > 1)
cout << maxChar << " - " << maxCount << endl;
else
cout << "No Duplicates Present" << endl;
}

int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while (T--) {
int n;
cout << "Enter size of array: ";
cin >> n;
vector<char> arr(n);
cout << "Enter array elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

findMaxOccurrence(arr, n);
}
return 0;
OUTPUT:

Name:Rohan Section:L1 Roll No. 44


Name:Rohan Section:L1 Roll No. 44
PROBLEM STATEMENT 2: Given an unsorted array of integers, design an algorithm and
implement it using a program tofind whether two elements exist such that their sum is equal to
the given key element. (TimeComplexity = O(n log n)).

SOURCE CODE: -
#include <iostream>
#include <vector>
using namespace std;

void merge(vector<int>& a, int left, int mid, int right) {


int n1 = mid - left + 1, n2 = right - mid;
vector<int> aleft(n1), aright(n2);
for (int i = 0; i < n1; i++) aleft[i] = a[left + i];
for (int i = 0; i < n2; i++) aright[i] = a[mid + 1 + i];

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (aleft[i] <= aright[j]) {
a[k++] = aleft[i++];
} else {
a[k++] = aright[j++];
}
}
while (i < n1) a[k++] = aleft[i++];
while (j < n2) a[k++] = aright[j++];
}

void mergeSort(vector<int>& a, int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}

int main() {
int T;
cout << "Enter number of test cases: ";
cin >> T;
while (T--) {
int n;
cout << "Enter size of array: ";
cin >> n;
vector<int> a(n);
cout << "Enter array elements: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}

mergeSort(a, 0, n - 1);

int target;
cout << "Enter target value: ";
cin >> target;

int left = 0, right = n - 1;


Name:Rohan Section:L1 Roll No. 44
bool found = false;

while (left < right) {


int sum = a[left] + a[right];
if (sum == target) {
cout << a[left] << " " << a[right] << endl;
found = true;
break;
} else if (sum < target) {
left++;
} else {
right--;
}
}

if (!found) {
cout << "No such elements exist" << endl;
}
}
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 3: You have been given two sorted integer arrays of size m and n.
Design an algorithm and implement it using a program to find list of elements which are
common to both. (TimeComplexity = O(m+n)).
SOURCE CODE: -

#include <iostream>

int main() {
int m, n;

printf("Enter size of first array: ");


scanf("%d", &m);
int a[m];
printf("Enter array elements: ");
for (int i = 0; i < m; i++) {
scanf("%d", &a[i]);
}

printf("Enter size of second array: ");


scanf("%d", &n);
int b[n];
printf("Enter array elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &b[i]);
}
int i = 0, j = 0;
while (i < m && j < n) {
if (a[i] == b[j]) {
printf("%d %d", a[i],b[j]);
i++;
j++;
} else if (a[i] < b[j]) {
i++;
} else {
j++;
}
}
printf("\n");
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 1: Given a (directed/undirected) graph, design an algorithm and
implement it using a program to find if a path exists between two given vertices or not. (Hint:
use DFS).
SOURCE CODE:
#include <iostream>
#include <vector>
using namespace std;
void dfs(int node, const vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int i = 0; i < graph.size(); i++) {
if (graph[node][i] == 1 && !visited[i]) {
dfs(i, graph, visited);}}}
int main() {
int n;
cout << "Enter number of nodes: ";
cin >> n;

vector<vector<int>> graph(n, vector<int>(n));


cout << "Enter adjacency matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> graph[i][j];
}
}
int src, dest;
cout << "Enter source and destination (1-based): ";
cin >> src >> dest;

src--; dest--; // Convert to 0-based indexing

vector<bool> visited(n, false);


dfs(src, graph, visited);

if (visited[dest]) {
cout << "Yes Path Exists\n";
} else {
cout << "No Such Path Exists\n";
}}
OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 2: Given a graph, design an algorithm and implement it using a
program to find if a graph is bipartite or not. (Hint: use BFS)
SOURCE CODE:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

bool isBipartite(const vector<vector<int>>& graph, int n) {


vector<int> color(n, -1);

for (int start = 0; start < n; start++) {


if (color[start] == -1) {
queue<int> q;
color[start] = 0;
q.push(start);

while (!q.empty()) {
int u = q.front(); q.pop();
for (int v = 0; v < n; v++) {
if (graph[u][v]) {
if (color[v] == -1) {
color[v] = 1 - color[u];
q.push(v);
} else if (color[v] == color[u]) {
return false;
}
}
}
}
}
}
return true;
}

int main() {
int n;
cout << "Enter number of nodes: ";
cin >> n;

vector<vector<int>> graph(n, vector<int>(n));


cout << "Enter adjacency matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> graph[i][j];
}
}

if (isBipartite(graph, n)) {
cout << "Yes Bipartite\n";
} else {
cout << "Not Bipartite\n";
}

return 0;
}

Name:Rohan Section:L1 Roll No. 44


OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 3: Given a directed graph, design an algorithm and implement it
using a program to find whether cycle exists in the graph or not.
SOURCE CODE:
#include <iostream>
#include <vector>
using namespace std;

bool dfsCycle(int node, const vector<vector<int>>& adj, vector<bool>& visited, vector<bool>&


recStack) {
visited[node] = true;
recStack[node] = true;

for (int v = 0; v < adj.size(); v++) {


if (adj[node][v]) {
if (!visited[v] && dfsCycle(v, adj, visited, recStack))
return true;
else if (recStack[v])
return true;
}
}

recStack[node] = false;
return false;
}

bool isCyclic(const vector<vector<int>>& adj, int n) {


vector<bool> visited(n, false);
vector<bool> recStack(n, false);

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


if (!visited[i]) {
if (dfsCycle(i, adj, visited, recStack))
return true;
}
}
return false;
}

int main() {
int n;
cout << "Enter number of vertices: ";
cin >> n;

vector<vector<int>> adj(n, vector<int>(n));


cout << "Enter adjacency matrix (" << n << " x " << n << "):\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> adj[i][j];

if (isCyclic(adj, n))
cout << "Yes Cycle Exists\n";
else
cout << "No Cycle Exists\n";

return 0;
}

Name:Rohan Section:L1 Roll No. 44


OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 1: After end term examination, Akshay wants to party with his
friends. All his friends are living as paying guest and it has been decided to first gather at
Akshay’s house and then move towards party location. The problem is that no one knows the
exact address of his house in the city. Akshay as a computer science wizard knows how to apply
his theory subjects in his real life and came up with an amazing idea to help his friends. He
draws a graph by looking in to location of his house and his friends’ location (as a node in the
graph) on a map. He wishes to find out shortest distance and path covering that distance from
each of his friend’s location to his house and then whatsapp them this path so that they can
reach his house in minimum time. Akshay has developed the program that implements
Dijkstra’s algorithm but not sure about correctness of results. Can you also implement the same
algorithm and verify the correctness of Akshay’s results? (Hint: Print shortest path and
distance from friends’ location to Akshay’s house).

SOURCE CODE:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int minDistance(const vector<int>& dist, const vector<bool>& visited, int V) {


int minVal = INT_MAX, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] < minVal) {
minVal = dist[v];
minIndex = v;
}
}
return minIndex;
}

void printPath(const vector<int>& parent, int j) {


if (parent[j] == -1) {
cout << j + 1;
return;
}
printPath(parent, parent[j]);
cout << " " << j + 1;
}

void dijkstra(const vector<vector<int>>& graph, int src, int V) {


vector<int> dist(V, INT_MAX);
vector<bool> visited(V, false);
vector<int> parent(V, -1);

dist[src] = 0;

for (int count = 0; count < V - 1; count++) {


int u = minDistance(dist, visited, V);
if (u == -1) break;
visited[u] = true;

for (int v = 0; v < V; v++) {


if (!visited[v] && graph[u][v] && dist[u] != INT_MAX &&
dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
Name:Rohan Section:L1 Roll No. 44
}
}

for (int i = 0; i < V; i++) {


cout << "Node " << i + 1 << ": ";
if (dist[i] == INT_MAX) {
cout << "No Path" << endl;
} else {
printPath(parent, i);
cout << " : " << dist[i] << endl;
}
}
}

int main() {
int V;
cout << "Enter number of vertices: ";
cin >> V;

vector<vector<int>> graph(V, vector<int>(V));


cout << "Enter adjacency matrix (" << V << " x " << V << "):\n";
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
cin >> graph[i][j];

int source;
cout << "Enter source vertex (Akshay's house, 1-based): ";
cin >> source;

cout << "Shortest paths to source " << source << ":\n";
dijkstra(graph, source - 1, V); // Convert to 0-based indexing

return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 2: Design an algorithm and implement it using a program to solve
previous question's problem using Bellman- Ford's shortest path algorithm.
SOURCE CODE:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

struct Edge {
int u, v, weight;
};

void printPath(const vector<int>& parent, int j) {


if (parent[j] == -1) {
cout << j + 1;
return;
}
printPath(parent, parent[j]);
cout << " " << j + 1;
}

void bellmanFord(const vector<vector<int>>& graph, int V, int src) {


vector<int> dist(V, INT_MAX);
vector<int> parent(V, -1);
vector<Edge> edges;

// Convert adjacency matrix to edge list


for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0) {
edges.push_back({u, v, graph[u][v]});
}
}
}

dist[src] = 0;

// Relax all edges V-1 times


for (int i = 1; i <= V - 1; i++) {
for (const auto& edge : edges) {
int u = edge.u, v = edge.v, w = edge.weight;
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
parent[v] = u;
}
}
}

// Check for negative-weight cycles


for (const auto& edge : edges) {
if (dist[edge.u] != INT_MAX && dist[edge.u] + edge.weight < dist[edge.v]) {
cout << "Graph contains a negative weight cycle!" << endl;
return;
}
}

// Print result
Name:Rohan Section:L1 Roll No. 44
for (int i = 0; i < V; i++) {
cout << "Node " << i + 1 << ": ";
if (dist[i] == INT_MAX) {
cout << "No Path" << endl;
} else {
printPath(parent, i);
cout << " : " << dist[i] << endl;
}
}
}

int main() {
int V;
cout << "Enter number of vertices: ";
cin >> V;

vector<vector<int>> graph(V, vector<int>(V));


cout << "Enter adjacency matrix (" << V << " x " << V << "):\n";
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
cin >> graph[i][j];

int src;
cout << "Enter source vertex (Akshay's house, 1-based): ";
cin >> src;

cout << "Shortest paths to source " << src << " using Bellman-Ford:\n";
bellmanFord(graph, V, src - 1); // Convert to 0-based index

return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 3 : Given a directed graph with two vertices ( source and
destination). Design an algorithm and implement it using a program to find the weight of the
shortest path from source to destination with exactly k edges on the path.
SOURCE CODE
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

#define INF INT_MAX

// Recursive function with memoization


int shortestPathKEdges(const vector<vector<int>>& graph, int u, int v, int k,
vector<vector<vector<int>>>& dp) {
if (k == 0 && u == v) return 0;
if (k == 0) return INF;
if (dp[u][v][k] != -1) return dp[u][v][k];

int res = INF;

for (int i = 0; i < graph.size(); i++) {


if (graph[u][i] != 0) {
int subPath = shortestPathKEdges(graph, i, v, k - 1, dp);
if (subPath != INF) {
res = min(res, graph[u][i] + subPath);
}
}
}

return dp[u][v][k] = res;


}

int main() {
int n;
cout << "Enter number of vertices: ";
cin >> n;

vector<vector<int>> graph(n, vector<int>(n));


cout << "Enter adjacency matrix (" << n << " x " << n << "):\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> graph[i][j];

int src, dest, k;


cout << "Enter source, destination, and number of edges k (1-based indexing): ";
cin >> src >> dest >> k;

src--; dest--; // Convert to 0-based

vector<vector<vector<int>>> dp(n, vector<vector<int>>(n, vector<int>(k + 1, -1)));

int result = shortestPathKEdges(graph, src, dest, k, dp);


if (result == INF)
cout << "No path of exactly " << k << " edges exists from " << src + 1 << " to " << dest + 1 <<
endl;
else
cout << "Shortest path from " << src + 1 << " to " << dest + 1 << " with exactly " << k << "
Name:Rohan Section:L1 Roll No. 44
edges: " << result << endl;

return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 1: Assume that a project of road construction to connect some cities
is given to your friend. Map of these cities and roads which will connect them (after
construction) is provided to him in the form of a graph. Certain amount of rupees is associated
with construction of each road. Your friend has to calculate the minimum budget required for
this project. The budget should be designed in such a way that the cost of connecting the cities
should be minimum and number of roads required to connect all the cities should be minimum
(if there are N cities then only N-1 roads need to be constructed). He asks you for help. Now, you
have to help your friend by designing an algorithm which will find minimum cost required to
connect these cities. (use Prim's algorithm)
SOURCE CODE:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int findMinVertex(const vector<int>& key, const vector<bool>& mstSet, int n) {


int minVal = INT_MAX, minIndex = -1;
for (int i = 0; i < n; i++) {
if (!mstSet[i] && key[i] < minVal) {
minVal = key[i];
minIndex = i;
}
}
return minIndex;
}

void primMST(const vector<vector<int>>& graph, int n) {


vector<int> key(n, INT_MAX);
vector<int> parent(n, -1);
vector<bool> mstSet(n, false);
key[0] = 0;

for (int count = 0; count < n - 1; count++) {


int u = findMinVertex(key, mstSet, n);
mstSet[u] = true;
for (int v = 0; v < n; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
parent[v] = u;
}
}
}

int totalCost = 0;
for (int i = 1; i < n; i++) {
cout << parent[i] + 1 << " - " << i + 1 << " : " << graph[i][parent[i]] << endl;
totalCost += graph[i][parent[i]];
}
cout << "Minimum cost to connect all cities: " << totalCost << endl;
}

int main() {
int n;
cin >> n;
vector<vector<int>> graph(n, vector<int>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
Name:Rohan Section:L1 Roll No. 44
cin >> graph[i][j];
primMST(graph, n);
return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44


PROBLEM STATEMENT 2: Implement the previous problem using Kruskal's algorithm.
SOURCE CODE:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int findMinVertex(const vector<int>& key, const vector<bool>& mstSet, int n) {


int minVal = INT_MAX, minIndex = -1;
for (int i = 0; i < n; i++) {
if (!mstSet[i] && key[i] < minVal) {
minVal = key[i];
minIndex = i;
}
}
return minIndex;
}

void primMST(const vector<vector<int>>& graph, int n) {


vector<int> key(n, INT_MAX);
vector<int> parent(n, -1);
vector<bool> mstSet(n, false);
key[0] = 0;

for (int count = 0; count < n - 1; count++) {


int u = findMinVertex(key, mstSet, n);
mstSet[u] = true;
for (int v = 0; v < n; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
parent[v] = u;
}
}
}

int totalCost = 0;
for (int i = 1; i < n; i++) {
cout << parent[i] + 1 << " - " << i + 1 << " : " << graph[i][parent[i]] << endl;
totalCost += graph[i][parent[i]];
}
cout << "Minimum cost to connect all cities: " << totalCost << endl;
}

int main() {
int n;
cin >> n;
vector<vector<int>> graph(n, vector<int>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> graph[i][j];
primMST(graph, n);
return 0;
}

OUTPUT:
Name:Rohan Section:L1 Roll No. 44
Name:Rohan Section:L1 Roll No. 44
PROBLEM STATEMENT 3: Assume that same road construction project is given to another
person. The amount he will earn from this project is directly proportional to the budget of the
project. This person is greedy, so he decided to maximize the budget by constructing those roads
who have highest construction cost. Design an algorithm and implement it using a program to
find the maximum budget required for the project.
SOURCE CODE:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Edge {
int u, v, weight;
};

int findParent(int node, vector<int>& parent) {


if (parent[node] == node) {
return node;
}
return parent[node] = findParent(parent[node], parent);
}

void unionSets(int u, int v, vector<int>& parent, vector<int>& rank) {


int parentU = findParent(u, parent);
int parentV = findParent(v, parent);

if (parentU != parentV) {
if (rank[parentU] > rank[parentV]) {
parent[parentV] = parentU;
} else if (rank[parentU] < rank[parentV]) {
parent[parentU] = parentV;
} else {
parent[parentV] = parentU;
rank[parentU]++;
}
}
}

void kruskalMaximizingBudget(int n, const vector<Edge>& edges) {


vector<int> parent(n);
vector<int> rank(n, 0);

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


parent[i] = i;
}

vector<Edge> mst;
int totalCost = 0;

vector<Edge> sortedEdges = edges;


sort(sortedEdges.begin(), sortedEdges.end(), [](const Edge& a, const Edge& b) {
return a.weight > b.weight;
});

for (const auto& edge : sortedEdges) {


int u = edge.u;
int v = edge.v;
Name:Rohan Section:L1 Roll No. 44
int weight = edge.weight;

if (findParent(u, parent) != findParent(v, parent)) {


mst.push_back(edge);
totalCost += weight;
unionSets(u, v, parent, rank);
}
}

for (const auto& edge : mst) {


cout << edge.u + 1 << " - " << edge.v + 1 << " : " << edge.weight << endl;
}
cout << "Maximum cost to connect all cities: " << totalCost << endl;
}

int main() {
int n, m;
cin >> n >> m;

vector<Edge> edges(m);

for (int i = 0; i < m; i++) {


cin >> edges[i].u >> edges[i].v >> edges[i].weight;
edges[i].u--;
edges[i].v--;
}

kruskalMaximizingBudget(n, edges);

return 0;
}

OUTPUT:

Name:Rohan Section:L1 Roll No. 44

You might also like