0% found this document useful (0 votes)
12 views37 pages

Daaaa

The document describes a program to implement counting sort. It contains the code to find the maximum element, create a count array, update the counts, build the sorted output array, and copy it back to the original array. It also provides sample input and output showing it sorts an array of numbers.

Uploaded by

Raghav
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)
12 views37 pages

Daaaa

The document describes a program to implement counting sort. It contains the code to find the maximum element, create a count array, update the counts, build the sorted output array, and copy it back to the original array. It also provides sample input and output showing it sorts an array of numbers.

Uploaded by

Raghav
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/ 37

COLLEGE OF TECHNOLOGY AND ENGINEERING

NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 9.
Object: Write a program to implement Counting sort.

#include <iostream>
#include <vector>

void countingSort(std::vector<int>& arr) {


if (arr.empty()) return;

// Find the maximum element in the array


int max_element = *std::max_element(arr.begin(), arr.end());

// Create a count array to store the count of each element


std::vector<int> count(max_element + 1, 0);

// Count the occurrences of each element


for (int num : arr) {
count[num]++;
}

// Update the count array to store the cumulative count of each element
for (int i = 1; i <= max_element; ++i) {
count[i] += count[i - 1];
}

// Create a temporary array to store the sorted output


std::vector<int> output(arr.size());

// Build the sorted array


for (int i = arr.size() - 1; i >= 0; --i) {
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

output[count[arr[i]] - 1] = arr[i];

count[arr[i]]--;
}

// Copy the sorted elements back to the original array


for (size_t i = 0; i < arr.size(); ++i) {
arr[i] = output[i];
}
}

int main() {
std::vector<int> arr = {4, 2, 2, 8, 3, 3, 1};
std::cout << "Original array:";
for (int num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

countingSort(arr);

std::cout << "Sorted array:";


for (int num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

return 0;
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

OUTPUT:-

PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) {


g++ countingsort.cpp -o countingsort } ; if ($?) { .\countingsort }
Original array: 4 2 2 8 3 3 1
Sorted array: 1 2 2 3 3 4 8
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 10.
Object: Write a program to implement radix sort.
#include <iostream>
#include <vector>
#include <algorithm>

int getMax(std::vector<int>& arr) {


int max = arr[0];
for (size_t i = 1; i < arr.size(); i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

void countingSort(std::vector<int>& arr, int exp) {


std::vector<int> output(arr.size());
std::vector<int> count(10, 0);

// Store count of occurrences in count[]


for (size_t i = 0; i < arr.size(); i++) {
count[(arr[i] / exp) % 10]++;
}

for (int i = 1; i < 10; i++) {


count[i] += count[i - 1];
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

// Build the output array


for (int i = arr.size() - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Copy the output array to arr[], so that arr[] now


// contains sorted numbers according to the current digit
for (size_t i = 0; i < arr.size(); i++) {
arr[i] = output[i];
}
}

void radixSort(std::vector<int>& arr) {

int max = getMax(arr);


for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}

int main() {
std::vector<int> arr = {170, 45, 75, 90, 802, 24, 2, 66};
std::cout << "Original array:";
for (int num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

radixSort(arr);
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

std::cout << "Sorted array:";


for (int num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

return 0;
}
OUTPUT:-
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\"
; if ($?) { g++ redix.cpp -o redix } ; if ($?) { .\redix }
Original array: 170 45 75 90 802 24 2 66
Sorted array: 2 24 45 66 75 90 170 802
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 11.
Object: Write a program to implement BUCKET sort.

#include <iostream>
#include <vector>
#include <algorithm>

void bucketSort(std::vector<double>& arr) {


int n = arr.size();

// Create buckets
std::vector<std::vector<double>> buckets(n);

// Put array elements in different buckets


for (int i = 0; i < n; i++) {
int bucket_index = n * arr[i];
buckets[bucket_index].push_back(arr[i]);
}

// Sort individual buckets


for (int i = 0; i < n; i++) {
std::sort(buckets[i].begin(), buckets[i].end());
}

// Concatenate all buckets into arr[]


int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i][j];
}
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

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

std::vector<double> arr(n);
std::cout << "Enter the elements (between 0 and 1): ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}

std::cout << "Original array:";


for (double num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

bucketSort(arr);

std::cout << "Sorted array:";


for (double num : arr) {
std::cout << " " << num;
}
std::cout << std::endl;

return 0;
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

OUTPUT:-

PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\"


; if ($?) { g++ BUCKET.cpp -o BUCKET } ; if ($?) { .\BUCKET }
Enter the number of elements: 5
Enter the elements (between 0 and 1): 0 0.2 0.1 0.6 0.4
Original array: 0 0.2 0.1 0.6 0.4
Sorted array: 0 0.1 0.2 0.4 0.6
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 12.
Object: Write a program to Implement Longest Common Subsequence.

Code:
#include <iostream>
#include <cstring> // for memset
using namespace std;

const int MAX = 1e5;

void lcs(string a, string b, int n, int m) {


int dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp)); // Initialize dp array with zeros

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


for (int j = 1; j <= m; j++) {
if (a[i - 1] == b[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}

int index = dp[n][m];


char lcs[index + 1];
lcs[index] = '\0';

int i = n, j = m;
while (i > 0 && j > 0) {
if (a[i - 1] == b[j - 1]) {
lcs[index - 1] = a[i - 1];
i--;
j--;
index--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR


j--;
}
}

cout << "Total length of LCS is: " << dp[n][m] << endl;
cout << "LCS of " << a << " and " << b << " is " << lcs << endl;
}

int main() {
string a, b;
cout << "Enter string 1: " << endl;
cin >> a;
cout << "Enter string 2: " << endl;
cin >> b;
int n = a.length();
int m = b.length();
lcs(a, b, n, m);
return 0;
}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
lcs.cpp - lcs } ; if ($?) { .\lcs }
Enter string 1:
abcd
Enter string 2:
defgabc
Total length of LCS is: 3
LCS of abcd and defgabc is abc
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 13.
Object: Write a program to implement matrix chain multiplication.
#include <iostream>
#include <climits>
#include <vector>
using namespace std;

// Function to find the minimum number of scalar multiplications needed


// to compute the matrix chain product of matrices from i to j
int matrixChainOrder(vector<int>& p, int n) {
vector<vector<int>> dp(n, vector<int>(n, 0));

// dp[i][j] will store the minimum number of scalar multiplications


// needed to compute the matrix chain product from matrix i to matrix j
for (int len = 2; len < n; len++) {
for (int i = 1; i < n - len + 1; i++) {
int j = i + len - 1;
dp[i][j] = INT_MAX;
for (int k = i; k < j; k++) {
int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
if (cost < dp[i][j]) {
dp[i][j] = cost;
}
}
}
}

// The result is stored in dp[1][n-1]


return dp[1][n - 1];
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

int main() {
vector<int> dimensions = {10, 30, 5, 60};
int n = dimensions.size();

cout << "Minimum number of scalar multiplications needed: " << matrixChainOrder(dimensions, n)
<< endl;

return 0;
}
OUTPUT :-
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\"
; if ($?) { g++ BUCKET.cpp -o BUCKET } ; if ($?) { .\BUCKET }
Minimum number of scalar multiplications needed: 4500
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 14.
Object: WAP to Implement Travelling Salesman Problem
Code:
// CPP program to implement traveling salesman
// problem using naive approach.
#include <bits/stdc++.h>
using namespace std;
#define V 4

// implementation of traveling Salesman Problem


int travllingSalesmanProblem(int graph[][V], int s)
{
// store all vertex apart from source vertex
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);

// store minimum weight Hamiltonian Cycle.


int min_path = INT_MAX;
do
{

// store current Path weight(cost)


int current_pathweight = 0;

// compute current path weight


int k = s;
for (int i = 0; i < vertex.size(); i++)
{
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];

// update minimum
min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

// Driver Code
int main()
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

{15, 35, 0, 30},


{20, 25, 30, 0}};
int s = 0;
cout << travllingSalesmanProblem(graph, s) << endl;
return 0;
}

OUTPUT:

PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++


tsp.cpp
tsp } ; if ($?) { .\tsp }
80
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 15.
Object: WAP to Implement 01 knapsack problem using Dynamic programming.

Code:
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5;

int max(int a, int b) { return (a > b) ? a : b; }


int dp[100][1000];
int knapsack(int W, int wt[], int val[], int n)
{
if (n < 0)
return 0;
if (dp[n][W] != -1)
{
return dp[n][W];
}

if (wt[n] > W)
{
dp[n][W] = knapsack(W, wt, val, n - 1);
return dp[n][W];
}
else
{
dp[n][W] = max(knapsack(W, wt, val, n - 1), val[n] + knapsack(W - wt[n], wt, val, n - 1));
return dp[n][W];
}
}
int main()
{
memset(dp, -1, sizeof(dp));
cout << "Enter number of elements " << endl;
int n, W;
cin >> n;
int w[n], v[n];
cout << "Weight of every elements " << endl;
for (int i = 0; i < n; i++)
{
cin >> w[i];
}
cout << "Value of every elements respective to weights: " << endl;
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
cout << "Total Weights: " << endl;
cin >> W;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

cout << "Max Value: " << endl;


cout << knapsack(W, w, v, n);
return 0;
}

OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
knap.cpp -o knap } ; if ($?) { .\knap }

Enter number of elements


4
Weight of every elements
3457
Value of every elements respective to weights:
10 30 40 20
Total Weights:
10
Max Value:
70
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 16.
Object: Write a program to implement Fractional k - napsack.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Structure to represent an item


struct Item {
int weight;
int value;
double density;

Item(int w, int v) : weight(w), value(v) {


density = (double)value / weight;
}
};

// Comparison function to sort items by their density in non-increasing order


bool compare(Item a, Item b) {
return a.density > b.density;
}

// Function to solve the fractional knapsack problem


double fractionalKnapsack(int capacity, vector<Item>& items) {
// Sort items by their density in non-increasing order
sort(items.begin(), items.end(), compare);

double totalValue = 0.0;


int currentWeight = 0;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

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


if (currentWeight + items[i].weight <= capacity) {
// Take the whole item if it fits into the knapsack
totalValue += items[i].value;
currentWeight += items[i].weight;
} else {
// Take a fraction of the item if it doesn't fit completely
int remainingWeight = capacity - currentWeight;
totalValue += items[i].density * remainingWeight;
break; // No need to consider remaining items
}
}

return totalValue;
}

int main() {
int capacity, n;
cout << "Enter the capacity of the knapsack: ";
cin >> capacity;

cout << "Enter the number of items: ";


cin >> n;

vector<Item> items;
cout << "Enter weight and value for each item:" << endl;
for (int i = 0; i < n; ++i) {
int weight, value;
cin >> weight >> value;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

items.push_back(Item(weight, value));
}

double maxValue = fractionalKnapsack(capacity, items);


cout << "Maximum value in the knapsack: " << maxValue << endl;

return 0;
}
OUTPUT:-
Enter the capacity of the knapsack: 12
Enter the number of items: 5
Enter weight and value for each item:
1
2
5
6
8
8
9
4
5
10
Maximum value in the knapsack: 19
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 17.
Object: Write a program to implement BIN tracking.
#include <iostream>
#include <vector>

using namespace std;

void firstFit(vector<int>& items, int binCapacity) {


vector<int> bins;
for (int item : items) {
bool packed = false;
for (int& bin : bins) {
if (bin + item <= binCapacity) {
bin += item;
packed = true;
break;
}
}
if (!packed) {
bins.push_back(item);
}
}
cout << "Number of bins used: " << bins.size() << endl;
cout << "Items packed into bins:" << endl;
for (int i = 0; i < bins.size(); ++i) {
cout << "Bin " << i + 1 << ": ";
cout << bins[i] << " ";
cout << endl;
}
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

int main() {
vector<int> items = {4, 8, 1, 4, 2, 5};
int binCapacity = 10;
cout << "Bin capacity: " << binCapacity << endl;
firstFit(items, binCapacity);
return 0;
}
OUTPUT:-
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\"
; if ($?) { g++ BIN.CPP -o BIN } ; if ($?) { .\BIN }
Bin capacity: 10
Number of bins used: 3
Items packed into bins:
Bin 1: 9
Bin 2: 10
Bin 3: 5
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 18.
Object: Write a program to implement DFS.

Code:
#include <bits/stdc++.h>
using namespace std;

void dfs(int node, vector<vector<int>> adj, vector<bool> &vis)


{
vis[node] = true;
cout << node << " ";
for (auto x : adj[node])
{
if (vis[x])
{
;
}
else
{
dfs(x, adj, vis);
}
}
}
void DFS(vector<vector<int>> adj, int n)
{

vector<bool> vis(n + 1, false);

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


{
if (!vis[i])
{
dfs(i, adj, vis);
}
}
}
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n);
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
cout << "DFS of Given Graph is as follows: " << endl;
DFS(adj, n);
return 0;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
dfs.cpp -o dfs } ; if ($?) { .\dfs }
56
01
02
13
14
24
34
DFS of Given Graph is as follows:
01342
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 19.
Object: Write a program to implement BFS.

Code:
#include <bits/stdc++.h>
using namespace std;

vector<int> bfsOfGraph(int V, vector<int> adj[])


{
vector<int> ans;
vector<bool> vis(V + 1, false);
queue<int> q;
q.push(0);
vis[0] = true;
while (!q.empty())
{
int node = q.front();
q.pop();
ans.push_back(node);
for (auto it : adj[node])
{
if (!vis[it])
{
q.push(it);
vis[it] = true;
}
}
}
return ans;
}

int main()
{
int V, E;
cin >> V >> E;
vector<int> adj[V];
for (int i = 0; i < E; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
vector<int> ans = bfsOfGraph(V, adj);
cout << "BFS of Given Graph is as follows" << endl;
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
cout << endl;
return 0;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
bfs.cpp -o bfs } ; if ($?) { .\bfs }
56
01
02
13
14
24
34
BFS of Given Graph is as follows
01234
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 20.
Object: Write a program to implement Prim's algorithm.

Code:
#include <bits/stdc++.h>
using namespace std;
// Function to find sum of weights of edges of the Minimum Spanning Tree.
void spanningTree(int V, vector<vector<int>> adj[])
{
int n = V;
int parent[n];
int keys[n];
bool mstSet[n];
for (int i = 0; i < n; i++)
{
parent[i] = -1;
keys[i] = INT_MAX;
mstSet[i] = false;
}
keys[0] = 0;
parent[0] = -1;
for (int i = 0; i < n - 1; i++)
{
int mini = INT_MAX, u;

for (int v = 0; v < n; v++)


{
if (mstSet[v] == false && keys[v] < mini)
{
mini = keys[v];
u = v;
}
}
mstSet[u] = true;
for (auto it : adj[u])
{
int v = it[0];
int weight = it[1];

if (mstSet[v] == false && weight < keys[v])


{
parent[v] = u, keys[v] = weight;
}
}
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += keys[i];
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

cout << "Edge \tWeight\n";


for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << " \t" << keys[i] << " \n";
cout << "Total Weight of MST" << endl;
cout << sum << endl;
}
int main()
{
int V, E;
cin >> V >> E;
vector<vector<int>> adj[V];
int i = 0;
while (i++ < E)
{
int u, v, w;
cin >> u >> v >> w;
vector<int> t1, t2;
t1.push_back(v);
t1.push_back(w);
adj[u].push_back(t1);
t2.push_back(u);
t2.push_back(w);
adj[v].push_back(t2);
}
spanningTree(V, adj);
return 0;
}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
prime.cpp -o prime } ; if ($?) { .\prime }
57
012
036
123
138
145
247
349
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Total Weight of MST
16
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 21.
Object: Write a program to implement Kruskal's Algorithm.
Code:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int u;
int v;
int wt;
node(int first, int second, int weight)
{
u = first;
v = second;
wt = weight;
}
};
bool comp(node a, node b)
{
return a.wt < b.wt;
}
int findPar(int u, vector<int> &parent)
{
if (u == parent[u])
return u;
return parent[u] = findPar(parent[u], parent);
}
void unionn(int u, int v, vector<int> &parent, vector<int> &rank)
{
u = findPar(u, parent);
v = findPar(v, parent);
if (rank[u] < rank[v])
{
parent[u] = v;
}
else if (rank[v] < rank[u])
{
parent[v] = u;
}
else
{
parent[v] = u;
rank[u]++;
}
}
void kruskals(vector<node> edges, int N)
{
sort(edges.begin(), edges.end(), comp);
vector<int> parent(N);
for (int i = 0; i < N; i++)
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

parent[i] = i;
vector<int> rank(N, 0);
int cost = 0;
vector<pair<pair<int, int>, int>> mst;
for (auto it : edges)
{if (findPar(it.v, parent) != findPar(it.u, parent)){cost += it.wt;mst.push_back({{it.u,
it.v},it.wt});unionn(it.u, it.v, parent, rank);}}
cout << "Edge \tWeight\n";
for (auto it : mst)
cout << it.first.first << " - " << it.first.second << " \t" << it.second << " \n";
cout << "Total weight of MST" << endl;
cout << cost << endl;
}
int main()
{
int N, m;
cin >> N >> m;
vector<node> edges;
for (int i = 0; i < m; i++)
{
int u, v, wt;
cin >> u >> v >> wt;
edges.push_back(node(u, v, wt));
}
kruskals(edges, N);
return 0;
}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
kruskal.cpp -o kruskal } ; if ($?) { .\kruskal }
57
012
036
123
138
145
247
349
Edge Weight
0-1 2
1-2 3
1-4 5
0-3 6
Total weight of MST
16
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 22.
Object: Write a program to implement Dijkstra algorithm.

Code:
#include <bits/stdc++.h>
using namespace std;
vector<int> dijkstra(int n, vector<vector<int>> adj[], int src)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> distTo(n, INT_MAX);
distTo[src] = 0;
pq.push(make_pair(0, src));
while (!pq.empty())
{
int dist = pq.top().first;
int prev = pq.top().second;
pq.pop();
for (auto it : adj[prev])
{
int next = it[0];
int nextDist = it[1];

if (distTo[next] > distTo[prev] + nextDist)


{
distTo[next] = distTo[prev] + nextDist;
pq.push(make_pair(distTo[next], next));
}
}
}
return distTo;
}
int main()
{

int V, E;
cin >> V >> E;
vector<vector<int>> adj[V];
int i = 0;
while (i++ < E)
{
int u, v, w;
cin >> u >> v >> w;
vector<int> t1, t2;
t1.push_back(v);
t1.push_back(w);
adj[u].push_back(t1);
t2.push_back(u);
t2.push_back(w);
adj[v].push_back(t2);
}
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

int S;
cin >> S;
vector<int> res = dijkstra(V, adj, S);
cout << "Distance from source to each node: " << endl;
for (int i = 0; i < V; i++)
cout << "0->" << res[i] << " ";
cout << endl;

return 0;
}
OUTPUT:

PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++


dijkstra.cpp -o dijkstra } ; if ($?) { .\dijkstra }
21
019
0
Distance from source to each node:
0->0 0->9
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 23.
Object: Write a program to implement Bellman ford algorithm.

Code:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int u, v, wt;
node(int f, int s, int wait)
{
u = f;
v = s;
wt = wait;
}
};
void bellmanFord()
{
int N, m;
cin >> N >> m;
vector<node> edges;
for (int i = 0; i < m; i++)
{
int u, v, wt;
cin >> u >> v >> wt;
edges.push_back(node(u, v, wt));
}
int src;
cin >> src;
int inf = 1e9;
vector<int> dist(N, inf);
dist[src] = 0;
for (int i = 0; i <= N - 1; i++)
{
for (auto it : edges)
{
if (dist[it.u] + it.wt < dist[it.v])
{
dist[it.v] = dist[it.u] + it.wt;
}
}
}
int fl = 0;
for (auto it : edges)
{
if (dist[it.u] + it.wt < dist[it.v])
{
cout << "NegativeCycle" << endl;
fl = 1;
break;
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

}
}
if (!fl)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < N; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
}
int main()
{
bellmanFord();
return 0;
}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
21
019
0
Vertex Distance from Source
0 0
1 9
PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

Program 24.
Object: Write a program to implement Ford Fulkerson algorithm.

Code:
#include <bits/stdc++.h>
using namespace std;
#define V 6
bool bfs(int rGraph[V][V], int s, int t, int parent[])
{
bool visited[V];
memset(visited, 0, sizeof(visited));
queue<int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
while (!q.empty())
{
int u = q.front();
q.pop();

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


{
if (visited[v] == false && rGraph[u][v] > 0)
{
if (v == t)
{
parent[v] = u;
return true;
}
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
return false;
}
int fordFulkerson(int graph[V][V], int s, int t)
{
int u, v;
int rGraph[V][V];
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];
int parent[V];
int max_flow = 0; // There is no flow initially
while (bfs(rGraph, s, t, parent))
{
int path_flow = INT_MAX;
for (v = t; v != s; v = parent[v])
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

{
u = parent[v];
path_flow = min(path_flow, rGraph[u][v]);
}
for (v = t; v != s; v = parent[v])
{
u = parent[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}

// Add path flow to overall flow


max_flow += path_flow;
}

// Return the overall flow


return max_flow;
}
int main()
{
int graph[V][V] = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0,
0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}};

cout << "The maximum possible flow is "


<< fordFulkerson(graph, 0, 5);

return 0;
}
OUTPUT:
PS C:\Users\mukul\OneDrive\Desktop\New folder> cd "c:\Users\mukul\OneDrive\Desktop\New folder\" ; if ($?) { g++
ford.cpp -o ford } ; if ($?) { .\ford }

The maximum possible flow is 23


PS C:\Users\mukul\OneDrive\Desktop\New folder>
COLLEGE OF TECHNOLOGY AND ENGINEERING
NAME :- Mukul Bharat SUBJECT :- CS 362 (PCC): DESIGN & ANALYSIS OF ALGORITHMS

CLASS :- B.TECH. III YEAR

You might also like