Daa Codes
Daa Codes
#include<iostream>
#include<stdlib.h>
using namespace std;
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>
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;
a)CODE:-
#include<iostream>
} Item;
Item temp;
temp = a[max];
a[max]=a[i];
a[i] = temp;
}
}
}
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>
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;
}
};
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;
}
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>
a)CODE:-
#include<bits/stdc++.h>
#define n 5
using namespace std;
a)CODE-
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, cap;
cout << "Enter the number of items: ";
cin >> n;
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);
}
}
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;
{
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;
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;
/*
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
};
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;
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];
a)CODE:-
#include<iostream>
#include<cstdlib>
#include<ctime>
int main() {
int a[20], n, i;
cin >> n;
quick(a, 0, n - 1);
cout << "Sorted array is: ";
return 0;
int temp;
srand(time(NULL));
temp = a[left];
a[left] = a[pivot];
a[pivot] = temp;
pivot = left;
int l = left;
int r = right;
while (l < r) {
r--;
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;
temp = a[pivot];
a[pivot] = a[r];
a[r] = temp;
// Recursive calls for left and right sub-arrays
quick(a, r + 1, right);
b)Output Screenshot:-
20.Jarvis March (Convex
Hull)
Question. Jarvis March Algorithm for Convex Hull .
a)CODE:-
#include <iostream>
struct Point {
int x;
int y;
};
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;
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>
a)CODE:-
#include <iostream>