Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

Name: Parth Chawla

Registration Number: 21BCE2147


Cycle sheet 3
1.Maximum Subarray Sum
Question: Find the maximum profit for items with item bag capacity
a)CODE:-

#include<iostream>
#include<stdlib.h>
using namespace std;

int max(int a, int b)


{
return (a>b?a:b);
}

int crossSum(int a[],int high , int mid, int low)


{
int left = INT8_MIN; int s = 0;
for(int i = mid ; i >= low; i--)
{
s += a[i];
if(s>left)
{
left = s;
}
}
s=0;
int right = INT8_MIN ;
for(int i = mid+1 ; i <= high ; i++)
{
s+= a[i];
if(s > right)
{
right = s;
}
}
return left+right;
}

int maxSum(int a[], int low, int high)


{

if(low==high)
{
return a[low];
}
int mid = (low + high)/2;
int temp =
max(maxSum(a,low,mid),maxSum(a,mid+1,high));
return max(crossSum(a,high,mid,low),temp);
}

int main()
{
int n;
cout<<"Enter the number of elements in the array: ";
cin>>n;
int arr[n];
for(int i=0 ; i<n ; i++)
{
cout<<"Enter the number: ";
cin>>arr[i];
}
cout<<"The Maximum subarray sum is:
"<<maxSum(arr,0,n-1);
}

b)output screenshot:-
2.Karutsubha:-
Question: Find the product of 584 and 3546 using Karastuba
algorithm

a)CODE:-

#include<iostream>
#include<string>
#include<math.h>

using namespace std;

int Karatsuba(int a, int b)


{
string as = to_string(a);
string bs = to_string(b);
int alen = as.length();
int blen = bs.length();

if(alen == 1 && blen == 1)


{
return (a*b);
}
else{
int n = max(alen,blen);
while (alen!=n)
{
as = "0"+as;
alen = as.length();
}

while (blen!=n)
{
bs = "0"+bs;
blen = bs.length();
}

int a = stoi(as.substr(0,n/2));
int b = stoi(as.substr(n/2,n-n/2));
int c = stoi(bs.substr(0,n/2));
int d = stoi(bs.substr(n/2,n-n/2));
int x1 = Karatsuba(a,c);
int x2 = Karatsuba(a+b,c+d);
int x3 = Karatsuba(b,d);
int m = ceil(n/2.0);
return(x1*pow(10,m*2)+(x2-x3-x1)*pow(10,m) + x3);

}
}
int main(){
int a,b;
cout<<"Enter the first number : ";
cin>>a;
cout<<"Enter the second number : ";
cin>>b;

cout<<"The product of the two numbers is :


"<<Karatsuba(a,b);
}
b)Output Screenshot :
3.Fractional Knapsack:-
Question: Find the maximum profit for items with bag capacity given
where the weight and profit of each item is given.

a)CODE:-

#include<iostream>

using namespace std;

typedef struct node


{
int weight;
float val,ratio;

} Item;

void init(Item a[],int n)


{
for(int i = 0 ; i < n ; i++)
{
a[i].ratio = a[i].val / a[i].weight;
}

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


int max = i;
for(int j = i+1 ; j<n ; j++)
{
if(a[j].ratio > a[max].ratio){
max = j;
}
}

Item temp;
temp = a[max];
a[max]=a[i];
a[i] = temp;
}
}

void change(Item a[], int n , int cap){


float amt = 0;
for(int i = 0 ; i<n ;i++){
if(a[i].weight <= cap)
{
amt+=a[i].val;
cap-=a[i].weight;
}
else{
amt+=((float)cap/(float)a[i].weight)*a[i].val;
break;
}

}
cout<<"The final amount using Greedy Method is:
"<<amt<<endl;
}
int main(){

int n,cap;
cout<<"Enter the number of objects"<<endl;
cin>>n;
Item a[n];
for(int i = 0; i<n;i++)
{
cout<<"Enter the weight of"<<" object "<<i+1<<endl;

cin>>a[i].weight;
cout<<"Enter the value of"<<" object "<<i+1<<endl;
cin>>a[i].val;
}
cout<<"Enter the capacity of the knapsack"<<endl;
cin>>cap;
init(a,n);
change(a,n,cap);
}
b)Output Screenshot:-
4)Huffmann coding:-
Question: Find the Huffman code for the characters given with
character frequencies.

a)CODE:-

#include<queue>
#include<iostream>
#include<string>

using namespace std;

struct Node{
char letter;
int freq;
struct Node *left,*right;
Node(char l,int f)
{
letter = l;
freq = f;
left = NULL;
right = NULL;
}
};

struct compare{
bool operator()(Node *left, Node *right){
return left->freq > right->freq;
}
};

void printcode(Node *root,string s)


{
if(root != NULL)
{
if(root->letter!='*'){
cout<<root->letter<<"-->"<<s<<endl;
}
printcode(root->left,s+"0");
printcode(root->right,s+"1");
}
}

void Huffman(char a[],int f[],int n){


priority_queue<Node*,vector<Node*>,compare> pq;
for(int i = 0 ; i < n; i++){
pq.push(new Node(a[i],f[i]));
}
Node *lchild,*rchild;
while(pq.size()!=1){
lchild = pq.top();
pq.pop();
rchild = pq.top();
pq.pop();
Node* temp = new
Node('*',lchild->freq+rchild->freq);
temp->left = lchild;
temp->right = rchild;
pq.push(temp);
}
printcode(pq.top()," ");
}

int main(){
int n;
cout<<"Enter the number of characters:";
cin>>n;
char arr[n];
int freq[n];
for(int i = 0 ; i<n ; i++)
{
cout<<"Enter the character:";
cin>>arr[i];
cout<<"Enter the frequency:";
cin>>freq[i];
}
cout<<"The Huffman code for the above data
is"<<endl;
Huffman(arr,freq,n);
}
b)Output Screenshot:-
5.Matrix Chain Multiplication:-
Question: Find the multiplication order of the given matrices to get
minimum number of multiplications

a)CODE:-
#include<bits/stdc++.h>
using namespace std;

int main()
{
int n;
cout<<"Enter the number of matrices:"<<endl;
cin>>n;
int r[n+1]; int dp[n][n]; int b[n][n];
cout<<"Enter the array of order of matrices \n";
for(int i=0;i<=n;i++)
{
cin>>r[i];
}

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
dp[i][j]=0;
}
}
for(int diff=2;diff<=n;diff++)
{
for(int i=0;i<=n-diff;i++)
{
int j=i+diff-1; int min=INT_MAX;
for(int k=i;k<=j-1;k++)
{
int cost=dp[i][k]+dp[k+1][j]+r[i]*r[k+1]*r[j+1];
if(cost<min)
{
min=cost;
b[i][j] = k;
}
}
dp[i][j]=min;
}
}
cout<<"The minimum number of multiplications
possible are "<<dp[0][n-1];
}
b)Output Screenshot:-
6.N-Queens
Question: Write a program to place ‘n’ queens on a n*n chess board
such that no queens clash.

a)CODE:-
#include <iostream>
#include <stdlib.h>
using namespace std;
void solve(int);
bool issafe(int , int);
void print();
int n;
int chess[20][20];
bool found = false;

int main(){
cout<<"Enter number of Queens: ";
cin>>n;
solve(0); // start filling from the 0th column
if(!found)
cout<<"No Solution \n";
return 0;
}
void solve(int col){
if(col == n){ // if col==n , it means that all n queens
are placed
found = true;
print();
return;
}

//loop through the row so as to try to place the


queen right from 0th row onwards
for(int i=0; i<n; i++){
//checking if the current cell is safe to place a
queen
if(issafe(i,col)){
//set current value to 1 to mean that u have
placed a queen
chess[i][col] = 1;
//trying to place the next queen in the next
column
solve(col+1);
//backtrack - reset to 0 to mean that the queen
is removed
chess[i][col] = 0;
}
}
}

//to check whether the current position is safe or not


bool issafe(int row, int col){
//Check the same row but only upto the current cell
as the subsequent columns
// would not have been filled so far
//if the current cell =row, col, then the cells in the
same row will have
//indexes as (row,0),(row,1),(row,2) ....etc Hence
(i--) in the loop
for(int i=col; i>=0; i--){
if(chess[row][i] == 1)
return false;
}
//check the top diagonal
// if the current cell=row,col, then the cells in the top
diagonals will have
//indexes as (row-1,col-1),(row-2,col-2) etc....
Hence,(i--,j--) in the loop
for(int i=row, j=col; i>=0 && j>=0; i--,j--){
if(chess[i][j] == 1)
return false;
}

//check the bottom diagonal


// if the current cell=row,col, then the cells in the
bottom diagonals will have
//indexes as (row+1,col-1),(row+2,col-2) etc....
Hence,(i++,j--) in the loop
for(int i=row, j=col; i<n && j>=0; i++,j--){
if(chess[i][j] == 1)
return false;
}

//return true because it is safe


return true;
}

//funtion to display the board


void print(){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(chess[i][j] == 1)
cout<<" Q ";
else
cout<<" - ";
}
cout<<"\n";
}
cout<<"\n";
}
b)Output Screenshot:-
7.Subset Sum:-
Question: Find subset of elements that are selected from a given set
whose sum adds up to given number

a)CODE:-
#include<stack>
#include<iostream>
using namespace std;
stack<int> stck;
bool found=false;
void print()
{
stack<int> temp;
while(!stck.empty())
{
temp.push(stck.top());
stck.pop();
}
while(!temp.empty())
{
cout<<temp.top()<<" ";
stck.push(temp.top());
temp.pop();
}

}
void solve(int curr,int ind,int a[],int tar,int n)
{
if(curr>tar)
return;
if(curr==tar)
{
found=true;
cout<<"The combinations are: \n";
print();
cout<<endl;
return;
}
for(int i=ind;i<n;i++)
{
stck.push(a[i]);
solve(curr+a[i],i+1,a,tar,n);
stck.pop();
}
}

main()
{
// int a[]={1,3,5,2};
// int n=4,tar=6;
int n,target;
cout<<"Enter the number of elements: ";
cin>>n;
cout<<"Enter the target sum: ";
cin>>target;
int a[n];
for(int i = 0 ; i < n ; i++)
{
cout<<"Enter the number: ";
cin>>a[i];
}
solve(0,0,a,target,n);
if(found==false)
cout<<"no solution";
return 0;
}
b)Output Screenshot:-
8.Assembly line Scheduling
Question: Perform Assembly Line scheduling and find out the
minimum cost based on the input given by the user.

a)CODE:-

#include <bits/stdc++.h>

using namespace std;


int main() {
int n;
cout << "Enter the number of intermediate stations:
";
cin >> n;
int a[2][n], t[2][n - 1], e[2], x[2];
cout << endl << "Filling the station cost matrix" <<
endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
cout << "Enter the station cost: ";
cin >> a[i][j];
}
}
cout << "Filling the transfer cost matrix" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n - 1; j++) {
cout << "Enter the transfer cost: ";
cin >> t[i][j];
}
}
for (int i = 0; i < 2; i++) {
cout << "Enter the entry cost for path " << i << " ";
cin >> e[i];
cout << "Enter the exit cost for path " << i << " ";
cin >> x[i];
}
cout << endl << endl;
int path[2][n];
int dp[n][n];
// time taken to reach station 0 in assembly line 0
dp[0][0] = e[0] + a[0][0];
// time taken to reach station 0 in assembly line 1
dp[1][0] = e[1] + a[1][0];
for (int j = 1; j < n; j++) {
int first = dp[0][j - 1] + a[0][j];
int second = dp[1][j - 1] + t[1][j - 1] + a[0][j];
if (first <= second) {
dp[0][j] = first;
path[0][j] = 0;
} else {
dp[0][j] = second;
path[0][j] = 1;
}
first = dp[0][j - 1] + t[0][j - 1] + a[1][j];
second = dp[1][j - 1] + a[1][j];
if (first <= second) {
dp[1][j] = first;
path[1][j] = 0;
} else {
dp[1][j] = second;
path[1][j] = 1;
}
}
int last;
if (dp[0][n - 1] + x[0] < dp[1][n - 1] + x[1])
last = 0;
else
last = 1;
cout << "The minimum cost of production is: " <<
min(dp[0][n - 1] + x[0], dp[1][n - 1] + x[1]) << "\n";
int i = last;
cout << "exit should be reached from assembly line "
<< i << "\n";
for (int j = n - 1; j > 0; j--) {
i = path[i][j];
cout << "station " << j << " should be reached from
assembly line " << i << "\n";
}
return 0;
}
b)Output Screenshot:-
9.Graph Colouring:-
Question: Assign colors to the vertices such that no two adjacent
vertices have the same color for the graph given by the user in the
form of adjacency matrix.

a)CODE:-
#include<bits/stdc++.h>
#define n 5
using namespace std;

bool isSafe(int v,int c,int color[],int adj[][n])


{
for(int i=0;i<n;i++)
{
if(adj[v][i]==1 && c==color[i])
{
return false;
}
}
return true;
}

bool solve(int v,int m,int color[],int adj[][5])


{
if(v==n)
return true;
for(int i=1;i<=m;i++)
{
if(isSafe(v,i,color,adj))
{
color[v]=i;
if(solve(v+1,m,color,adj))
return true;
color[v]=0;
}
}
return false;
}

void print(int color[])


{
for(int i=0;i<n;i++)
{
cout<<"The color of the vertex "<<i<<" is
"<<color[i]<<endl;
}
}
int main()
{
int m;
cout<<"Enter the number of colors used ";
cin>>m;
int adj[n][n];
cout<<"Enter the adjacency matrix of the graph \n";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>adj[i][j];
}
}
int color[n];
for(int i=0;i<n;i++)
{
color[i]=0;
}
if(!solve(0,m,color,adj))
{
cout<<"doesn't exist";
}
else
print(color);
return 0;
}
b)Output Screenshot:-
10)0-1 Knapsack:-
Question: Find the maximum profit for given items with a given bag
capacity where the weight and profit of each item is given as

a)CODE-
#include <bits/stdc++.h>
using namespace std;

int main() {
int n, cap;
cout << "Enter the number of items: ";
cin >> n;

int wt[n], val[n];


cout << "Enter the weight and value of each item:\n";
for(int i=0; i<n; i++)
cin >> wt[i] >> val[i];

cout << "Enter the maximum capacity of the knapsack:


";
cin >> cap;

int dp[n+1][cap+1];
for(int i=0; i<n+1; i++)
dp[i][0] = 0;
for(int j=0; j<cap+1; j++)
dp[0][j] = 0;
for(int i=1; i<n+1; i++) {
for(int j=1; j<cap+1; j++) {
int notinclude = 0 + dp[i-1][j];
int include = INT_MIN;
if(wt[i-1] <= j)
include = val[i-1] + dp[i-1][j-wt[i-1]];
dp[i][j] = max(notinclude, include);
}
}

cout << "The maximum value of items that can be put


into the knapsack is: " << dp[n][cap] << endl;
cout << "Included items are:\n";
int row = n, col = cap;
while(row > 0 || col > 0) {
if(dp[row][col] != dp[row-1][col]) {
cout << "Item " << row << " with weight " <<
wt[row-1] << endl;
col -= wt[row-1];
}
row--;
}

return 0;
}
b)Output Screenshot:-
11.Longest Common Subsequence:-
Question: Find the longest common subsequence in given two
strings “speedy” and “steady”.

a)CODE:-

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

int main()
{
string s1;
string s2;
cout<<"Enter the first string\n";
cin>>s1;
cout<<"Enter the second string\n";
cin>>s2;
int m = s1.size();
int n = s2.size();
int dp[m+1][n+1];
int seq[m+1][n+1];
for(int i=0;i<m+1;i++)
for(int j=0;j<n+1;j++)
{
dp[i][j]=0;
seq[i][j]=0;
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1.at(i-1)==s2.at(j-1))
{
dp[i][j]= 1+dp[i-1][j-1];
seq[i][j]=3; //to denote that the value is obtained
from diagonal
}
else
{
int first=dp[i][j-1];
int second=dp[i-1][j];
dp[i][j]= first>second?first:second;
seq[i][j]= first>second?1:2; //1 to denote that the value
is obtained from left
} // 2 to denote that the value is
obtained from top cell
}
}
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<"\n";
}
cout<<"seq\n";
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
cout<<seq[i][j]<<" ";
}
cout<<"\n";
}
int last=seq[m][n];
string substring="";
int i=m,j=n;
while(i!=0 && j!=0)
{
if(last==3) // if 3, the characters in both strings match;
{

substring.append(s1.substr(i-1,1)); // so add that


char to the substring
i--; j--; //this is to move to the diagonally
previous cell
}
else if(last==1) //if 1, it means that value has come
from the left cell
j--; // so, decrement j to move to the left cell
else if(last==2) //if 2, it means that value has come
from the top cell
i--; // so, decrement i to move to the top cell
last=seq[i][j]; // value stored in that i-j th cell should
be checked in the next iteration
}
cout<<"common subsequence before reversing is
"<<substring<<"\n";
reverse(substring.begin(), substring.end());
cout<<"common subsequence after reversing is
"<<substring;
}
b)Output Screenshot:-
MODULE 3 & 4
12.Naive String Matching Algorithm:-
Question: Find the occurrence of a pattern ‘p’ in a given string ‘s’
using naïve string algorithm.
a)CODE:-
#include <bits/stdc++.h>
#include <string.h>
using namespace std;

int main()
{
string s,p;
cout<<"Enter the main string\n";
cin>>s;
cout<<"Enter the pattern\n";
cin>>p;
int slen = s.length();
int plen = p.length();
int flag = 0;

for(int i = 0; i <= slen-plen; i++)


{
int j = 0;
while(j < plen && p.at(j) == s.at(i+j))
{
j++;
}
if(j == plen)
{
cout <<"pattern exists at index " << i <<endl;
flag = 1;
}
}

if(flag == 0)
{
cout << "Pattern doesn't exist";
}

return 0;
}

b)Output Screenshot:-
13. KMP Algorithm:-
Question: Find the occurrence of a pattern ‘p’ in a given string ‘s’
using KMP algorithm.

a)CODE:-
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
void calcLPS(string p,int LPS[]){
LPS[0] = 0;
int i = 0,j=1;
while (j<p.length()){
if(p[i]==p[j])
{
LPS[j] = i+1;
i++; j++;
}
else{
if(i==0){
LPS[j] = 0;
j++;
}
else{
i = LPS[i-1];
}
}
}
}
int main()
{
string s,p;
cout<<"Enter the main string\n";
cin>>s;
cout<<"Enter the pattern\n";
cin>>p;
int slen = s.length();
int plen = p.length();
int LPS[plen];
calcLPS(p,LPS); // to build the LPS table
int i=0,j=0;
while(i<slen){
if(p[j]==s[i]){i++;j++;
}
if (j == plen) {
cout<<"pattern exists at index "<<i - plen <<' '; //
to print the index of the string where the pattern matches
j = LPS[j - 1];
}
else if (i < slen && p[j] != s[i]) {
if (j == 0)
i++;
else
j = LPS[j - 1];
}
} }
b)Output Screenshot:-
14.Rabin Karp Algorithm:-
Question: Find the occurrence of a pattern ‘p’ in a given string
‘s’ using Rabin Karp Algorithm.
a)CODE:-
#include<bits/stdc++.h>
#define prime 13
using namespace std;

int main()
{
string s,p;
cout<<"Enter the main string\n";
cin>>s;
cout<<"Enter the pattern\n";
cin>>p;
int plen = p.length();
int slen = s.length();
int ph=0,sh=0,h=1,maxchar=10;
for(int i=0;i<plen-1;i++)
h=(h*maxchar)%prime;
for(int i=0;i<plen;i++)
{
ph=(ph*maxchar+p[i]-65+1)%prime;
sh=(sh*maxchar+s[i]-65+1)%prime;
}
cout<<"hash value of the pattern"<<p<<" is
"<<ph<<endl;
cout<<"hash value of the window
"<<s.substr(0,plen)<<" is "<<sh<<endl;
for(int i=0;i<=slen-plen;i++)
{
if(ph==sh)
{
int flag=0,count=0;
for(int j=0;j<plen;j++)
{
if(s[i+j]==p[j])
{
flag=1;
count++;
}
else
break;
}
if(count==plen)
{
cout<<"Pattern occurs at index: "<<i<<endl;
}
}
if(i<slen-plen)
{

sh=((sh-(s[i]-65+1)*h)*maxchar+(s[i+plen]-65+1))%prime;
while(sh<0)
sh+=prime;
cout<<"hash value of the
window"<<s.substr(i+1,plen)<<" is "<<sh<<endl;
}
}
return 0;
}
b)Output Screenshot:-
15.Bellman Ford Algorithm
Question: Find the single source shortest path for the input graph.
Enter the graph as Adjacency matrix.

a)CODE:-
#include<bits/stdc++.h>
using namespace std;

struct edge
{
int source,dest; float wt;
};

int main()
{
int v,e;
cout<<"Enter number of vertices ";
cin>>v;
cout<<"Enter number of edges ";
cin>>e;
struct edge edges[e];
int d[v],start;
cout<<"Enter the source vertex ";
cin>>start;
cout<<"Enter the source, destination and weight of
each edge\n";
for(int i=0;i<e;i++)
{
cin>>edges[i].source>>edges[i].dest>>edges[i].wt;
}
for(int i=0;i<v;i++)
{
d[i]=INT_MAX;
}
d[start-1]=0;
for(int i=0;i<v-1;i++)
{
for(int j=0;j<e;j++)
{
int u=edges[j].source;
int v=edges[j].dest;
float w=edges[j].wt;
if(d[v-1]>d[u-1]+w)
{
d[v-1]=d[u-1]+w;
}
}
}
int flag=0;
for(int j=0;j<e;j++)
{
int u=edges[j].source;
int v=edges[j].dest;
float w=edges[j].wt;
if(d[v-1]>d[u-1]+w)
{
flag=1;
break;
}
}
if(flag==0)
{
for(int i=0;i<v;i++)
{
if(d[i]<100000)
{
cout<<start<<" -> "<<i+1<<" shortest path is
"<<d[i]<<"\n";
}
else
{
cout<<start<<" -> "<<i+1<<" shortest path is
infinity\n";
}
}
}
else
{
cout<<"No solution -ve weight cycle";
}
return 0;
}
b)Output Screenshot:-
16. Floyd Warshall Algorithm
Question: Find the shortest path between every pair of two vertices
for the input graph. Enter the graph as Adjacency matrix.

a)CODE:-
#include <bits/stdc++.h>
#define MAX 20
using namespace std;

struct path
{
char a[MAX];
int len;
} route[MAX][MAX]; // route matrix uses this structure
int cost[MAX][MAX];
int n;

int main()
{
int i, j, k, c, x, y;
int max_edges, origin, destin;
cout << "Enter number of nodes : ";
cin >> n;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
route[i][j].len = 0;
cost[i][j] = 999999; // initialize all entries in cost[][] to 0
}
}
max_edges = n * (n - 1);
for (i = 1; i <= max_edges; i++)
{
cout << "Enter edge - "<<i<<" ( 0 0 to quit ) : ";
cin >> origin >> destin;
if ((origin == 0) && (destin == 0))
break;
if (origin > n || destin > n || origin <= 0 || destin <= 0)
{
cout << "Invalid edge!\n";
i--;
}
else
{
cout << "Enter the cost: \n";
cin >> c; // only for a valid edge, read its cost
'c' and store it in the appropriate
cost[origin][destin] = c; // index of cost[ ][ ]
route[origin][destin].a[route[origin][destin].len++] =
origin + 48;
route[origin][destin].a[route[origin][destin].len++] =
destin + 48; // for storing origin node &
route[origin][destin].a[route[origin][destin].len]='\0';
//destination as characters in route[][]
}
}
// display
cout << "\nInitial Cost Matrix\n";
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
cout << cost[i][j] << " ";
cout << "\n";
}
for (i = 1; i <= n; i++) // 'i' index generates the 4
iterations needed for individually exploring routes via
//generates intermidiate(via) node
{ // 'j' index generates the row number of
the matrices // generates starting node
for (j = 1; j <= n; j++) // 'j' index generates the row
number of the matrices // generates ending node
{
for (k = 1; k <= n; k++) // 'k' index generates the 4
columns that are to be processed in each row
{
if (cost[j][k] > cost[j][i] + cost[i][k]) // if the route via
vertex 'i' is shorter, update the cost of that route
{
cost[j][k] = cost[j][i] + cost[i][k]; // in the cost matrix.
for (x = 0; x < route[j][i].len; x++)
route[j][k].a[x] = route[j][i].a[x]; // first copy
contents of route[j][i] to route[j][k]
for (y = 1; y < route[i][k].len; y++)
route[j][k].a[x - 1 + y] = route[i][k].a[y]; // next
append contents of route[i][k] to route[j][k]
route[j][k].a[x - 1 + y] = '\0';
route[j][k].len = route[j][i].len + route[i][k].len - 1;
}
}
}
}
cout << "\nFinal Cost Matrix\n";
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
cout << cost[i][j] << " ";
cout << "\n";
}
cout << "\nFinal Route Matrix\n";
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
cout << route[i][j].a << " ";
cout << "\n";
}
return 0;
}
a)Output Screenshot:-
17. Edmond Karp Algorithm
Question: Calculate the maxflow through the circuit entered by the
user in the form of a ‘n’ x ‘n’ matrix.

a)CODE:-
#include<bits/stdc++.h>
#define n 6
//#define n 4
using namespace std;

typedef struct Node {


int id;
int state; //status
int pred; //predecessor
}node;

/*
int res[n][n] = {
{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} //maxflow=23
};

int res[n][n]={
{0,3,2,0},{0,0,5,2},{0,0,0,3},{0,0,0,0}
};
*/
int res[n][n] = {
{0, 10, 0, 10, 0, 0},
{0, 0, 4, 2, 8, 0},
{0, 0, 0, 0, 0, 10},
{0, 0, 0, 0, 9, 0},
{0, 0, 6, 0, 0, 10},
{0, 0, 0, 0, 0, 0} //maxflow=19
};

bool bfs(node vert[], node source, node sink) {


node u;
int i, j;
queue<node> q;

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


vert[i].state = 0;
}

vert[source.id].state = 1; //source is visited


vert[source.id].pred = -1; //no parent for source
q.push(source); //enqueue source node

while(!q.empty()) {
u = q.front();
q.pop();
for(i = 0; i<n; i++) {
if(res[u.id][i] > 0 && vert[i].state == 0) {
q.push(vert[i]);
vert[i].pred = u.id;
vert[i].state = 1;
}
}
} // end of while
return (vert[sink.id].state == 1);
}
int main() {
node vert[n];
node source, sink;
for(int i = 0; i<n; i++) {
vert[i].id = i;
}

source.id = 0;
sink.id = n-1;
int maxflow = 0;
int u, v;

while(bfs(vert, source, sink)) { //find augmented path


using bfs
int augflow = INT_MAX;
for(v = sink.id; v != source.id; v=vert[v].pred) {
u = vert[v].pred;
augflow = augflow<res[u][v]?augflow:res[u][v];
}
for(v = sink.id; v != source.id; v=vert[v].pred) {
u = vert[v].pred;
res[u][v] -= augflow; //update residual capacity of
edges
res[v][u] += augflow; //update residual capacity of
reverse edges
}
/* cout<<"residue graph after each iteration\n";
for(int i = 0; i<n; i++) {
for(int j = 0; j<n; j++) {
cout<< res[i][j]<<" ";}
cout<<"\n";}*/
maxflow += augflow;
} //while
cout << "Maximum flow is: " << maxflow << endl;
}
b)Output Screenshot:-
18.Push Relabel Algorithm:-
Question: Calculate the maxflow through the circuit entered by the
user in the form of a ‘n’ x ‘n’ matrix.

a)CODE:-
#include <bits/stdc++.h>
using namespace std;
struct Vertex
{
int h;
int eflow;
};
int v, e;
int **cap, **flow;
struct Vertex *vert;
int getactivenode(int source, int sink)
{
for (int i = 1; i < v - 1; i++) // consider only the
intermediate nodes excluding source & sink
{
if (vert[i].eflow > 0) // eflow node
{
for (int j = 0; j < v; j++)
{
if (cap[i][j] != 0 || flow[i][j] != 0) // check both
cap[][] & flow[][] to find the neighbors
{
if (cap[i][j] != flow[i][j]) // check if there is
residual capacity
return i;
}
}
}
}
return -1;
}
void preflow(int s)
{
vert[s].h = v;
for (int i = 0; i < v; i++)
{
if (i != s && cap[s][i] != 0)
{
flow[s][i] = cap[s][i];
flow[i][s] = -cap[s][i];
vert[i].eflow += cap[s][i];
}
}
}
bool push(int u)
{
for (int i = 0; i < v; i++)
{
if (cap[u][i] != 0 || flow[u][i] != 0)
{
if (flow[u][i] == cap[u][i])
continue;
if (vert[u].h > vert[i].h)
{ // minimum of residual capacity[u][i] and eflow(u)
int Flow = cap[u][i] - flow[u][i] < vert[u].eflow ?
cap[u][i] - flow[u][i] : vert[u].eflow;
vert[u].eflow -= Flow;
vert[i].eflow += Flow;
flow[u][i] += Flow;
flow[i][u] -= Flow;
return true;
}
}
}
return false;
}
void relabel(int u)
{
int minh = INT_MAX;
for (int i = 0; i < v; i++)
{
if (cap[u][i] != 0 || flow[u][i] != 0)
{
if (cap[u][i] == flow[u][i])
continue;
if (vert[i].h < minh) // at the end of loop, height of
least height node is considered
{
minh = vert[i].h;
vert[u].h = minh + 1;
}
}
}
}
int maxFlow(int source, int sink)
{
preflow(source);
cout << "\nInitial capacity\n";
for (int i = 0; i < v; i++)
{
for (int j = 0; j < v; j++)
cout << cap[i][j] << " ";
cout << "\n";
}
int u = getactivenode(source, sink);
while (u !=
-1)
{
if (!push(u))
relabel(u);
u = getactivenode(source, sink);
}
return vert[sink].eflow;
}
int main()
{
cout << "Enter no. of vertices";
cin >> v;
// v=6;
cout << "Enter no. of edges";
cin >> e;
// e=10;
vert = new Vertex[v];
cap = new int *[v];
for (int i = 0; i < v; i++)
cap[i] = new int[v];
flow = new int *[v];
for (int i = 0; i < v; i++)
flow[i] = new int[v];

cout << "Enter edges and their capacity";


for (int i = 0; i < v; i++)
{
vert[i].h = 0;
vert[i].eflow = 0;
for (int j = 0; j < v; j++)
{
flow[i][j] = 0;
cap[i][j] = 0;
}
}
int x, y, c;
for (int i = 0; i < e; i++)
{
cin >> x >> y >> c;
cap[x][y] = c;
}
/* cap[0][1]=1;
cap[0][2]=100;
cap[1][2]=100;
cap[2][1]=1
;
cap[1][3]=100;
cap[2][3]=1;
*/
cout << "Enter source and sink";
int source, sink;
cin >> source >> sink;
cout << "The max flow is : " << maxFlow(source, sink);
cout << "\nfinal flow\n";
for (int i = 0; i < v; i++)
{
for (int j = 0; j < v; j++)
cout << flow[i][j] << " ";
cout << "\n";
}
}
b)Output Screenshot:-
MODULE 5 & 6
19.Randomized Quick Sort:-
Question: Perform Randomized Quick Sort.

a)CODE:-

#include<iostream>

#include<cstdlib>

#include<ctime>

using namespace std;

// Quick Sort function

void quick(int a[], int left, int right);

int main() {

int a[20], n, i;

cout << "Enter the number of elements in the array: ";

cin >> n;

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

for (i = 0; i < n; i++) cin >> a[i];

quick(a, 0, n - 1);
cout << "Sorted array is: ";

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

return 0;

void quick(int a[], int left, int right) {

int temp;

// Check if there is only one element or invalid range

if (left >= right) return;

// Generate random pivot index within range [left, right]

srand(time(NULL));

int pivot = (rand() % (right - left + 1)) + left;

// Swap the pivot element with the left-most element

temp = a[left];
a[left] = a[pivot];

a[pivot] = temp;

// Set pivot to the left-most index

pivot = left;

// Initialize left and right pointers

int l = left;

int r = right;

// Partition the array around the pivot element

while (l < r) {

// Find element on the right side smaller than the pivot

while (a[r] > a[pivot])

r--;

// Find element on the left side greater than or equal to the


pivot
while (a[l] <= a[pivot])

l++;

// If left and right pointers haven't crossed yet, swap the two
elements

if (l < r) {

temp = a[l];

a[l] = a[r];

a[r] = temp;

// Swap pivot element with the element at right pointer index

temp = a[pivot];

a[pivot] = a[r];

a[r] = temp;
// Recursive calls for left and right sub-arrays

quick(a, left, r - 1);

quick(a, r + 1, right);

b)Output Screenshot:-
20.Jarvis March (Convex
Hull)
Question. Jarvis March Algorithm for Convex Hull .

a)CODE:-
#include <iostream>

using namespace std;

struct Point {
int x;
int y;
};

int direction(Point p, Point q, Point r) {


int val = (r.x - p.x) * (q.y - p.y) - (q.x - p.x) * (r.y - p.y);

if (val == 0) return 0; // collinear


return (val > 0) ? 1 : 2; // clock or counterclock wise
}

void convexHull(Point points[], int n) {

if (n < 3) return;
bool included[n];
for (int i = 0; i < n; i++) included[i] = false;
int left = 0;
for (int i = 1; i < n; i++)
if (points[i].x < points[left].x) left = i;
int prev = left, curr;
do {
// Find the point 'curr' such that direction(prev, curr, i) is
// anti-clockwise for all points 'i'
curr = (prev + 1) % n;
for (int i = 0; i < n; i++)
if (direction(points[prev], points[curr], points[i]) == 2)
curr = i;

included[prev] = true;
prev = curr;

} while (prev != left);

cout << "The points in the convex hull are: ";


for (int i = 0; i < n; i++) {
if (included[i] != false) cout << "(" << points[i].x << ", " << points[i].y
<< ") ";
}
cout << endl;
}

int main() {
int n;
cout << "Enter the number of points: ";
cin >> n;
Point points[n];
cout << "Enter the coordinates of " << n << " points:\n";
for (int i = 0; i < n; i++) {
cin >> points[i].x >> points[i].y;
}
// Point points[] = { { 0, 3 }, { 2, 2 }, { 1, 1 }, { 2, 1 }, { 3, 0 }, { 0, 0 }, { 3, 3
} };

convexHull(points, n);

return 0;}
b)Output Screenshot:-
21.Hiring problem
Question. Hiring problem using Randomized Quick Sort:

a)CODE:-

#include <iostream>

#include <time.h>

#include <stdlib.h>

using namespace std;


struct candidate {
int rank, interview_status;
};
int main() {
int n, no_hired = 0;
// below code is for taking inputs from the user
cout << "enter the number of candidates: ";
cin >> n;
struct candidate * cand = new struct candidate[n];
cout << "enter the ranks: ";
for (int i = 0; i < n; i++) cin >> cand[i].rank;
int best = -1;
srand(time(0));
int index;
for (int i = 0; i < n; i++) {
do {
index = rand() % n; // since upper-lower=n-0=n
} while (cand[index].interview_status == 1);
// if the same number which was generated already is generated
again, call rand() again
cand[index].interview_status = 1; // cout<<"index "<<index<<"\n";
if (best == -1) {
best = index;
no_hired += 1;
} else if (cand[index].rank > cand[best].rank) {
best = index;
no_hired += 1;
}
}
cout << "nr of hired candidates is " << no_hired << "\n";
cout << "best candidate index and rank " << best << ", " <<
cand[best].rank;
return 0;
}
b)Output Screenshot:-
22.Line Segments Intersection
Question. Program to check whether two line segments intersect or
not:

a)CODE:-
#include <iostream>

using namespace std;


struct Point {
int x;
int y;
};
// Given three collinear points p, q, r, the function checks if // point q
lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r) {
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y)
&& q.y >= min(p.y, r.y)) return true;
return false;
}
// To find orientation of ordered triplet (p, q, r). // The function returns
following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r) {
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0)
return 0; // collinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
bool doIntersect(Point p1, Point q1, Point p2, Point q2) {
// Find the four orientations needed for general and // special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4) return true;
// Special Cases
// p1, q1 and p2 are collinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) return true;
// p1, q1 and q2 are collinear and q2 lies on segment p1q1
if (o2 == 0 && onSegment(p1, q2, q1)) return true;
// p2, q2 and p1 are collinear and p1 lies on segment p2q2if (o3 == 0
&& onSegment(p2, p1, q2)) return true;
// p2, q2 and q1 are collinear and q1 lies on segment p2q2
if (o4 == 0 && onSegment(p2, q1, q2)) return true;
return false; // Doesn't fall in any of the above cases
}
int main() {
// struct Point p1 = {1, 1}, q1 = {10, 1}; // struct Point p2 = {1, 2}, q2 =
{10, 2};
struct Point p1, q1, p2, q2;
cout << "Enter p1: " << endl;
cin >> p1.x;
cin >> p1.y;
cout << "Enter q1: " << endl;
cin >> q1.x;
cin >> q1.y;
cout << "Enter p2: " << endl;
cin >> p2.x;
cin >> p2.y;
cout << "Enter q2: " << endl;
cin >> q2.x;
cin >> q2.y;
doIntersect(p1, q1, p2, q2) ? cout << "Yes: Intersect\n" : cout << "No:
Do not intersect\n";
return 0;
}
b)Output Screenshot:-

You might also like