0% found this document useful (0 votes)
1 views

Algo

The document outlines a series of programming tasks focused on various algorithms, including search algorithms (Linear and Binary Search), sorting algorithms (Bubble, Insertion, Merge, Quick, Heap, Counting, Radix, and Bucket Sort), and Prim's Algorithm for finding the minimum spanning tree. Each program includes C++ code implementations along with user prompts for input and output statements. The document serves as a comprehensive guide for learning and implementing these algorithms in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Algo

The document outlines a series of programming tasks focused on various algorithms, including search algorithms (Linear and Binary Search), sorting algorithms (Bubble, Insertion, Merge, Quick, Heap, Counting, Radix, and Bucket Sort), and Prim's Algorithm for finding the minimum spanning tree. Each program includes C++ code implementations along with user prompts for input and output statements. The document serves as a comprehensive guide for learning and implementing these algorithms in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

INDEX

S.No Name of Program Date of Date of Sign


. Execution Submission

1. Write a program to perform


Linear Search.

2. Write a program to perform


Binary Search.

3. Write a program to implement


Bubble Sort.

4. Write a program to implement


Insertion Sort.

5. Write a program to implement


Merge Sort.

6. Write a program to implement


Quick Sort.
Program 01: Write a program to perform Linear Search.
Code:

#include <iostream>
using namespace std;
int main()
{
cout << "Arriyaan Ali Syed\n";
int arr[100], size;
int item, loc;
cout << "Enter the size of the array: ";
cin >> size;
cout << "Enter the elements of the array: " << endl;
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter item to search: " << endl;
cin >> item;
for (loc = 0; loc <= size; loc++)
{
if (arr[loc] == item)
{
cout << "element found at position:" << loc + 1 << endl;
return 0;
}
}
cout << "element not found!";
return 0;
}
Output:
Program 02: Write a program to perform Binary Search.
Code:
#include <iostream>
using namespace std;

int main()
{
int size, n;
int arr[100];
cout << "Arriyaan Ali Syed\n";
cout << "Enter the size of the array: ";
cin >> size;
cout << "Enter the elements of the sorted array: " << endl;
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter the element to search: ";
cin >> n;
int beg = 0, end = size - 1, mid;
while (beg <= end)
{
mid = (beg + end) / 2;
if (arr[mid] == n)
{
cout << "Element found at position: " << mid + 1 << endl;
return 0;
}
if (arr[mid] < n) {
beg = mid + 1;
}
else {
end = mid - 1;
}
}
cout << "Element not found!" << endl;
return 0;
}
Output:
Program 03: Write a program to perform Bubble Sort.
Code:
#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n)


{ for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
}

void printArray(int arr[], int n)


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

int main()
{
int n;
cout << "Arriyaan Ali Syed\n";

cout << "Enter the size of the array: ";


cin >> n;

int arr[n];

cout << "Enter " << n << " elements: ";


for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "Before sorting: ";
printArray(arr, n);

bubbleSort(arr, n);

cout << "After sorting: ";


printArray(arr, n);

return 0;
}

Output:
Program 04: Write a program to perform Insertion Sort.
Code:
#include <iostream>
using namespace std;

void insert(int a[], int n) {


int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while (j >= 0 && a[j] > temp) {


a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = temp;
}
}

void printArr(int a[], int n) {


for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}

int main() {
int size, a[100];
cout << "Arriyaan Ali Syed\n";

cout << "Enter size of array: ";


cin >> size;

if (size < 1 || size > 100) {


cout << "Invalid size. Please enter a value between 1 and 100." << endl;
return 1;
}

cout << "Enter elements of array: ";


for (int i = 0; i < size; i++) {
cin >> a[i];
}
cout << "Before sorting: " << endl;
printArr(a, size);

insert(a, size);

cout << "After sorting: " << endl;


printArr(a, size);

return 0;
}

Output:
Program 05: Write a program to perform Merge Sort.
Code:
#include <iostream>
using namespace std;

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


int n1 = mid - left + 1;
int 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) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
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);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
cout << "Arriyaan Ali Syed\n";
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Before sorting: ";
printArray(arr, n);
mergeSort(arr, 0, n - 1);
cout << "After sorting: ";
printArray(arr, n);

return 0;
}

Output:
Program 06: Write a program to perform Quick Sort.
Code:
#include <iostream>
using namespace std;

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;
}

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);
}
}

void printArray(int arr[], int n) {


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

int main() {
cout << "Arriyaan Ali Syed\n";
int n;
cout << "Enter the size of the array: ";
cin >> n;

int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

cout << "Before sorting: ";


printArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "After sorting: ";


printArray(arr, n);

return 0;
}

Output:
Program 07: Write a program to perform Heap Sort.
Code:

#include <iostream>
using namespace std;

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {


swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


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

int main() {
int n;
cout << "Arriyaan Ali Syed\n";
cout << "Enter the number of elements: ";
cin >> n;

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

cout << "Original array: ";


printArray(arr, n);

heapSort(arr, n);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

Output:
Program 08: Write a program to perform Counting Sort.
Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void countingSort(vector<int>& arr) {


if (arr.empty()) return;

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


int min_val = *min_element(arr.begin(), arr.end());
int range = max_val - min_val + 1;

vector<int> count(range, 0);


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

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


count[arr[i] - min_val]++;

for (int i = 1; i < range; i++)


count[i] += count[i - 1];

for (int i = arr.size() - 1; i >= 0; i--) {


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

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


arr[i] = output[i];
}

int main() {
int n;
cout << "Arriyaan Ali Syed\n";
cout << "Enter the number of elements: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];

cout << "Original array: ";


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

countingSort(arr);

cout << "Sorted array: ";


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

return 0;
}

Output:
Program 09: Write a program to perform Radix Sort.
Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int getMax(vector<int>& arr) {


return *max_element(arr.begin(), arr.end());
}

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


int n = arr.size();
vector<int> output(n);
vector<int> count(10, 0);

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


count[(arr[i] / exp) % 10]++;

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


count[i] += count[i - 1];

for (int i = n - 1; i >= 0; i--) {


output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

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


arr[i] = output[i];
}

void radixSort(vector<int>& arr) {


int max_val = getMax(arr);

for (int exp = 1; max_val / exp > 0; exp *= 10)


countingSort(arr, exp);
}

void printArray(vector<int>& arr) {


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

int main() {
int n;
cout << "Arriyaan Ali Syed\n";
cout << "Enter the number of elements: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];

cout << "Original array: ";


printArray(arr);

radixSort(arr);

cout << "Sorted array: ";


printArray(arr);

return 0;
}

Output:
Program 10: Write a program to perform Bucket Sort.
Code:

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

using namespace std;

void bucketSort(vector<float> &arr) {


int n = arr.size();
vector<vector<float>> buckets(n);

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


int index = n * arr[i];
buckets[index].push_back(arr[i]);
}

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


sort(buckets[i].begin(), buckets[i].end());
}

int index = 0;
for (int i = 0; i < n; i++) {
for (size_t j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i][j];
}
}
}

int main() {
int n;
cout << "Arriyaan Ali Syed\n";
cout << "Enter the number of elements: ";
cin >> n;

vector<float> arr(n);
cout << "Enter " << n << " floating-point numbers between 0 and 1: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
bucketSort(arr);

cout << "Sorted array: ";


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

return 0;
}

Output:
Program 11: Write a program to perform Prim’s Algorithm.
Code:

#include <iostream>
#include <vector>
#include <limits.h>

using namespace std;

#define INF INT_MAX

int findMinVertex(vector<int>& key, vector<bool>& inMST, int V) {


int minKey = INF, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!inMST[v] && key[v] < minKey) {
minKey = key[v];
minIndex = v;
}
}
return minIndex;
}

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


vector<int> parent(V, -1);
vector<int> key(V, INF);
vector<bool> inMST(V, false);

key[0] = 0;

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


int u = findMinVertex(key, inMST, V);
inMST[u] = true;

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


if (graph[u][v] && !inMST[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
cout << "Minimum Spanning Tree (Prim's Algorithm):\n";
for (int i = 1; i < V; i++) {
cout << parent[i] << " - " << i << " : " << graph[i][parent[i]] << "\n";
}
}

int main() {
int V;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of vertices: ";
cin >> V;

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

cout << "Enter adjacency matrix (use 0 for no edge):\n";


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
cin >> graph[i][j];
}
}

primMST(graph, V);

return 0;
}

Output:
Program 12: Write a program to perform Kruskal’s Algorithm.
Code:

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

using namespace std;

struct Edge {
int src, dest, weight;
};

struct Subset {
int parent, rank;
};

bool compareEdges(Edge a, Edge b) {


return a.weight < b.weight;
}

int find(vector<Subset>& subsets, int i) {


if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

void unionSets(vector<Subset>& subsets, int x, int y) {


int rootX = find(subsets, x);
int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank)


subsets[rootX].parent = rootY;
else if (subsets[rootX].rank > subsets[rootY].rank)
subsets[rootY].parent = rootX;
else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}
void kruskalMST(vector<Edge>& edges, int V) {
vector<Edge> result;
vector<Subset> subsets(V);

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


subsets[v].parent = v;
subsets[v].rank = 0;
}

sort(edges.begin(), edges.end(), compareEdges);

int e = 0, i = 0;
while (e < V - 1 && i < edges.size()) {
Edge nextEdge = edges[i++];
int x = find(subsets, nextEdge.src);
int y = find(subsets, nextEdge.dest);

if (x != y) {
result.push_back(nextEdge);
unionSets(subsets, x, y);
e++;
}
}

cout << "Minimum Spanning Tree (Kruskal's Algorithm):\n";


for (auto edge : result)
cout << edge.src << " - " << edge.dest << " : " << edge.weight << "\n";
}

int main() {
int V, E;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of vertices and edges: ";
cin >> V >> E;

vector<Edge> edges(E);
cout << "Enter edges (src dest weight):\n";
for (int i = 0; i < E; i++)
cin >> edges[i].src >> edges[i].dest >> edges[i].weight;

kruskalMST(edges, V);

return 0;
}
Output:
Program 13: Write a program to perform 0/1 Knapsack Algorithm.
Code:
#include <iostream>
#include <vector>

using namespace std;

int knapsack(int W, vector<int>& weights, vector<int>& values, int n) {


vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));

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


for (int w = 0; w <= W; w++) {
if (weights[i - 1] <= w)
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}

return dp[n][W];
}

int main() {
int n, W;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of items: ";
cin >> n;
cout << "Enter knapsack capacity: ";
cin >> W;

vector<int> values(n), weights(n);


cout << "Enter values and weights of items:\n";
for (int i = 0; i < n; i++)
cin >> values[i] >> weights[i];

int maxValue = knapsack(W, weights, values, n);


cout << "Maximum value in Knapsack = " << maxValue << endl;

return 0;
}
Output:
Program 14: Write a program to perform Fractional Knapsack Algorithm.
Code:

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

using namespace std;

struct Item {
int value, weight;
};

bool compare(Item a, Item b) {


double ratio1 = (double)a.value / a.weight;
double ratio2 = (double)b.value / b.weight;
return ratio1 > ratio2;
}

double fractionalKnapsack(int W, vector<Item>& items, int n) {


sort(items.begin(), items.end(), compare);

double totalValue = 0.0;

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


if (W >= items[i].weight) {
totalValue += items[i].value;
W -= items[i].weight;
} else {
totalValue += (double)items[i].value * ((double)W / items[i].weight);
break;
}
}

return totalValue;
}

int main() {
int n, W;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of items: ";
cin >> n;
cout << "Enter knapsack capacity: ";
cin >> W;

vector<Item> items(n);
cout << "Enter values and weights of items:\n";
for (int i = 0; i < n; i++)
cin >> items[i].value >> items[i].weight;

double maxValue = fractionalKnapsack(W, items, n);


cout << "Maximum value in Knapsack = " << maxValue << endl;

return 0;
}

Output:
Program 15: Write a program to perform LCS Algorithm.
Code:

#include <iostream>
#include <vector>

using namespace std;

int lcs(string X, string Y) {


int m = X.length();
int n = Y.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

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


for (int j = 1; j <= n; j++) {
if (X[i - 1] == Y[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}

return dp[m][n];
}

int main() {
cout << "Arriyaan Ali Syed\n";
string X, Y;
cout << "Enter first string: ";
cin >> X;
cout << "Enter second string: ";
cin >> Y;

int length = lcs(X, Y);


cout << "Length of Longest Common Subsequence: " << length << endl;

return 0;
}
Output:
Program 16: Write a program to perform BFS Algorithm.
Code:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class Graph {
int V;
vector<vector<int>> adj;

public:
Graph(int V) {
this->V = V;
adj.resize(V);
}

void addEdge(int u, int v) {


adj[u].push_back(v);
adj[v].push_back(u); // For an undirected graph
}

void BFS(int start) {


vector<bool> visited(V, false);
queue<int> q;

visited[start] = true;
q.push(start);

cout << "BFS Traversal: ";


while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";

for (int neighbor : adj[node]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << endl;
}
};

int main() {
cout << "Arriyaan Ali Syed\n";
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;

Graph g(V);

cout << "Enter edges (u v):" << endl;


for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}

int start;
cout << "Enter starting vertex for BFS: ";
cin >> start;

g.BFS(start);

return 0;
}

Output:
Program 17: Write a program to perform DFS Algorithm.
Code:

#include <iostream>
#include <vector>

using namespace std;

class Graph {
int V;
vector<vector<int>> adj;

public:
Graph(int V) {
this->V = V;
adj.resize(V);
}

void addEdge(int u, int v) {


adj[u].push_back(v);
adj[v].push_back(u); // For an undirected graph
}

void DFSUtil(int node, vector<bool>& visited) {


visited[node] = true;
cout << node << " ";

for (int neighbor : adj[node]) {


if (!visited[neighbor])
DFSUtil(neighbor, visited);
}
}

void DFS(int start) {


vector<bool> visited(V, false);
cout << "DFS Traversal: ";
DFSUtil(start, visited);
cout << endl;
}
};
int main() {
int V, E;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of vertices and edges: ";
cin >> V >> E;

Graph g(V);

cout << "Enter edges (u v):" << endl;


for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}

int start;
cout << "Enter starting vertex for DFS: ";
cin >> start;

g.DFS(start);

return 0;
}

Output:
Program 18: Write a program to perform Dijkstra’s Algorithm.
Code:

#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

typedef pair<int, int> pii;

class Graph {
int V;
vector<vector<pii>> adj;

public:
Graph(int V) {
this->V = V;
adj.resize(V);
}

void addEdge(int u, int v, int weight) {


adj[u].push_back({v, weight});
adj[v].push_back({u, weight}); // For an undirected graph
}

void dijkstra(int src) {


priority_queue<pii, vector<pii>, greater<pii>> pq;
vector<int> dist(V, INT_MAX);

pq.push({0, src});
dist[src] = 0;

while (!pq.empty()) {
int u = pq.top().second;
pq.pop();

for (auto neighbor : adj[u]) {


int v = neighbor.first;
int weight = neighbor.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}

cout << "Vertex Distance from Source " << src << endl;
for (int i = 0; i < V; i++)
cout << i << " \t\t " << dist[i] << endl;
}
};

int main() {
int V, E;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of vertices and edges: ";
cin >> V >> E;

Graph g(V);

cout << "Enter edges (u v weight):" << endl;


for (int i = 0; i < E; i++) {
int u, v, weight;
cin >> u >> v >> weight;
g.addEdge(u, v, weight);
}

int start;
cout << "Enter starting vertex for Dijkstra's algorithm: ";
cin >> start;

g.dijkstra(start);

return 0;
}
Output:
Program 19: Write a program to perform Bellman-Ford Algorithm.
Code:

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

struct Edge {
int src, dest, weight;
};

class Graph {
int V, E;
vector<Edge> edges;

public:
Graph(int V, int E) {
this->V = V;
this->E = E;
}

void addEdge(int u, int v, int weight) {


edges.push_back({u, v, weight});
}

void bellmanFord(int src) {


vector<int> dist(V, INT_MAX);
dist[src] = 0;

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


for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v])


dist[v] = dist[u] + weight;
}
}
// Detect negative-weight cycles
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {


cout << "Graph contains a negative-weight cycle!" << endl;
return;
}
}

cout << "Vertex Distance from Source " << src << endl;
for (int i = 0; i < V; i++)
cout << i << " \t\t " << dist[i] << endl;
}
};

int main() {
int V, E;
cout << "Arriyaan Ali Syed\n";
cout << "Enter number of vertices and edges: ";
cin >> V >> E;

Graph g(V, E);

cout << "Enter edges (u v weight):" << endl;


for (int i = 0; i < E; i++) {
int u, v, weight;
cin >> u >> v >> weight;
g.addEdge(u, v, weight);
}

int start;
cout << "Enter starting vertex for Bellman-Ford algorithm: ";
cin >> start;

g.bellmanFord(start);

return 0;
}
Output:
Program 20: Write a program to perform Ford-Fulkerson Algorithm.
Code:

#include <iostream>
#include <vector>
#include <climits>
#include <queue>

using namespace std;

#define V 6 // Number of vertices in the graph

// BFS to check if there is a path from source to sink in the residual graph
bool bfs(vector<vector<int>>& residualGraph, int source, int sink, vector<int>& parent) {
vector<bool> visited(V, false);
queue<int> q;

q.push(source);
visited[source] = true;
parent[source] = -1;

while (!q.empty()) {
int u = q.front();
q.pop();

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


if (!visited[v] && residualGraph[u][v] > 0) {
if (v == sink) {
parent[v] = u;
return true;
}
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
return false;
}

// Ford-Fulkerson Algorithm
int fordFulkerson(vector<vector<int>>& graph, int source, int sink) {
vector<vector<int>> residualGraph = graph;
vector<int> parent(V);
int maxFlow = 0;

while (bfs(residualGraph, source, sink, parent)) {


int pathFlow = INT_MAX;

for (int v = sink; v != source; v = parent[v]) {


int u = parent[v];
pathFlow = min(pathFlow, residualGraph[u][v]);
}

for (int v = sink; v != source; v = parent[v]) {


int u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}

maxFlow += pathFlow;
}

return maxFlow;
}

int main() {
cout << "Arriyaan Ali Syed\n";
vector<vector<int>> graph = {
{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}
};

int source = 0, sink = 5;

cout << "The maximum possible flow is: " << fordFulkerson(graph, source, sink) << endl;

return 0;
}
Output:
Program 21: Write a program to perform TSP Algorithm.
Code:

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

#define INF INT_MAX


#define N 4 // Number of cities

int dp[N][1 << N]; // DP table for memoization


int dist[N][N] = { // Distance matrix (graph)
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

// Function to solve TSP using bitmask DP


int tsp(int pos, int mask) {
if (mask == (1 << N) - 1) // All cities visited
return dist[pos][0]; // Return to starting city

if (dp[pos][mask] != -1) // Check if result is already computed


return dp[pos][mask];

int minCost = INF;

for (int city = 0; city < N; city++) {


if ((mask & (1 << city)) == 0) { // If city is not visited
int newCost = dist[pos][city] + tsp(city, mask | (1 << city));
minCost = min(minCost, newCost);
}
}

return dp[pos][mask] = minCost; // Store result and return


}

int main() {
cout << "Arriyaan Ali Syed\n";
for (int i = 0; i < N; i++)
for (int j = 0; j < (1 << N); j++)
dp[i][j] = -1; // Initialize DP table with -1

cout << "The minimum cost of visiting all cities is: " << tsp(0, 1) << endl;
return 0;
}

Output:
Program 22: Write a program to perform Floyd-Warshall Algorithm.
Code:

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

#define INF 99999 // A large number representing infinity


#define V 4 // Number of vertices

// Function to implement the Floyd-Warshall Algorithm


void floydWarshall(int graph[V][V]) {
int dist[V][V];

// Initialize the solution matrix same as the input graph matrix


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];

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


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}

// Print the shortest distance matrix


cout << "Shortest distances between every pair of vertices:\n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
cout << "INF\t";
else
cout << dist[i][j] << "\t";
}
cout << endl;
}
}
int main() {
cout << "Arriyaan Ali Syed\n";
int graph[V][V] = {
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0}
};

floydWarshall(graph);

return 0;
}

Output:
S.No. Name of Program Date of Date of Sign
Execution Submission

You might also like