Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Maximum Subarray Sum Using Divide and Conquer Approach: Code: - (Without Array Elements Print)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 49

Maximum Subarray Sum Using Divide and Conquer

Approach
Code :-[without array elements print]
#include <stdio.h>
#include <limits.h>
 
int max(int x, int y) {
    return (x > y) ? x : y;
}
 
int maximum_sum(int nums[], int low, int high)
{
    if (high <= low) {
        return nums[low];
    }
 
    int mid = (low + high) / 2;
 
    int left_max = INT_MIN;
    int sum = 0;
    for (int i = mid; i >= low; i--)
    {
        sum += nums[i];
        if (sum > left_max) {
            left_max = sum;
        }
    }
 
    
    int right_max = INT_MIN;
    sum = 0;    // reset sum to 0
    for (int i = mid + 1; i <= high; i++)
    {
        sum += nums[i];
        if (sum > right_max) {
            right_max = sum;
        }
    }
 
    
    int max_left_right = max(maximum_sum(nums, low, mid),
                            maximum_sum(nums, mid + 1, high));
 
   
    return max(max_left_right, left_max + right_max);
}
 
int main(void)
{
    int arr[] = { 2, -4, 1, 9, -6, 7, -3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printf("The maximum sum of the subarray is %d",
            maximum_sum(arr, 0, n - 1));
 
    return 0;
}
---------------------------------

Time Complexity :- T(n) = 2T(n/2) + O(n) = O(n.log(n))


[with array elements print]
Code :-

#include <stdio.h>

#include <limits.h>

int max(int a, int b) {

return (a > b) ? a : b;

int maxCrossingSum(int arr[], int l, int m, int r, int *start, int *end) {

int sum = 0;

int left_sum = INT_MIN;

for (int i = m; i >= l; i--) {

sum = sum + arr[i];

if (sum > left_sum) {

left_sum = sum;

*start = i;

sum = 0;

int right_sum = INT_MIN;

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

sum = sum + arr[i];


if (sum > right_sum) {

right_sum = sum;

*end = i;

return left_sum + right_sum;

int maxSubarraySum(int arr[], int l, int r, int *start, int *end) {

if (l == r) {

*start = l;

*end = r;

return arr[l];

int m = l + (r - l) / 2;

int left_start, left_end;

int max_left_sum = maxSubarraySum(arr, l, m, &left_start, &left_end);

int right_start, right_end;

int max_right_sum = maxSubarraySum(arr, m + 1, r, &right_start, &right_end);

int cross_start, cross_end;

int max_cross_sum = maxCrossingSum(arr, l, m, r, &cross_start, &cross_end);

if (max_left_sum >= max_right_sum && max_left_sum >= max_cross_sum) {

*start = left_start;

*end = left_end;
return max_left_sum;

} else if (max_right_sum >= max_left_sum && max_right_sum >= max_cross_sum) {

*start = right_start;

*end = right_end;

return max_right_sum;

} else {

*start = cross_start;

*end = cross_end;

return max_cross_sum;

int main() {

int n,i;

printf("enter the no of elements in the array:");

scanf("%d",&n);

int arr[n];

printf("\nenter the elements in the array :");

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

scanf("%d",&arr[i]);

int start, end;

int max_sum = maxSubarraySum(arr, 0, n - 1, &start, &end);

printf("Maximum subarray sum is %d\n", max_sum);


printf("Subarray with maximum sum is:");

for (int i = start; i <= end; i++) {

printf(" %d", arr[i]);

printf("\n");

return 0;
}
 

Assembly Line Scheduling Problem Using Dynamic


Programming
Code:-

 S[i,j]: The jth station on ith assembly line


 a[i,j]: Time required at station S[i,j], because every station has some dedicated job that needs
to done.
 e[i]: Entry time of product on assembly line i [here i= 1,2]
 x[i]: Exit time from assembly line i
 t[i,j]: Time required to transit from station S[i,j] to the other assembly line.

Code :-
// A C program to find minimum possible time by the car chassis to complete
#include <stdio.h>
#define NUM_LINE 2
//#define NUM_STATION 4
int NUM_STATION;
int e[NUM_LINE],x[NUM_LINE];

int min(int a, int b) { return a < b ? a : b; }

int carAssembly(int a[NUM_LINE][NUM_STATION], int t[NUM_LINE][NUM_STATION], int


*e, int *x)
{
int T1[NUM_STATION], T2[NUM_STATION], i;

T1[0] = e[0] + a[0][0]; // time taken to leave first station in line 1


T2[0] = e[1] + a[1][0]; // time taken to leave first station in line 2

for (i = 1; i < NUM_STATION; ++i)


{
T1[i] = min(T1[i-1] + a[0][i], T2[i-1] + t[1][i] + a[0][i]);
T2[i] = min(T2[i-1] + a[1][i], T1[i-1] + t[0][i] + a[1][i]);
}

// Consider exit times and return minimum


return min(T1[NUM_STATION-1] + x[0], T2[NUM_STATION-1] + x[1]);
}

int main()
{
int i,j;
printf("enter the no of stations:");
scanf("%d",&NUM_STATION);
int a[NUM_LINE][NUM_STATION];
int t[NUM_LINE][NUM_STATION];
printf("\nenter the processing times:");
for(i=0;i<NUM_LINE;i++)
{
for(j=0;j<NUM_STATION;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nenter the transfer times:");

for(i=0;i<NUM_LINE;i++)
{
for(j=0;j<NUM_STATION;j++)
{
scanf("%d",&t[i][j]);
}
}

// int a[NUM_LINE][NUM_STATION] = {{4, 5, 3, 2},


// {2, 10, 1, 4}};
// int t[NUM_LINE][NUM_STATION] = {{0, 7, 4, 5},
// {0, 9, 2, 8}};
printf("\nenter the start times of line 1 and 2 respectively ");
for(i=0;i<NUM_LINE;i++)
{
scanf("%d",&e[i]);
}
printf("\nenter the exit times of line 1 and 2 respectively ");

for(i=0;i<NUM_LINE;i++)
{
scanf("%d",&x[i]);
}
// int e[NUM_LINE] = {10, 12}, x[NUM_LINE] = {18, 7};
printf("\nThe min time is :%d", carAssembly(a, t, e, x));

return 0; }
Longest Common Subsequence :-
(length of lcs and table and also the words print)
Code :-
#include <stdio.h>
#include <string.h>

#define MAX_LEN 100

int max(int a, int b) {


return a > b ? a : b;
}

int main() {
char str1[MAX_LEN], str2[MAX_LEN];
int len1, len2, i, j;

printf("Enter the first string: ");


scanf("%s", str1);
len1 = strlen(str1);

printf("Enter the second string: ");


scanf("%s", str2);
len2 = strlen(str2);

int dp[len1+1][len2+1];

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


for (j = 0; j <= len2; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
printf("The dynamic programming table is:\n");
for (i = 0; i <= len1; i++) {
for (j = 0; j <= len2; j++) {
printf("%d ", dp[i][j]);
}
printf("\n");
}

char lcs[MAX_LEN];
int index = dp[len1][len2];
lcs[index] = '\0';

i = len1;
j = len2;

while (i > 0 && j > 0) {


if (str1[i-1] == str2[j-1]) {
lcs[index-1] = str1[i-1];
i--;
j--;
index--;
} else if (dp[i-1][j] > dp[i][j-1]) {
i--;
} else {
j--;
}
}

printf("The longest common subsequence is: %s\n", lcs);


printf("\nlength in common is :%ld",strlen(lcs));
return 0;
}

KMP ALGORITHM :- C++


#include <iostream>
#include<string.h>
using namespace std;
void computeLPSArray(char* pat, int M, int* lps)
{
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0) {
len = lps[len - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps);\
int i = 0;
int j = 0;
while ((N - i) >= (M - j)) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
cout<<"The match is found: "<< i - j+1<<" - "<<i<<endl;
j = lps[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
int main()
{
char txt[100] ;
char pat[100] ;
cin>>txt>>pat;
KMPSearch(pat, txt);
return 0;
}
FLOYD WARSHALL ALGORITHM :-
Code :-
#include <stdio.h>
#include <stdlib.h>
int i=0;
#define INF 99999

void floyd_warshall(int **graph, int n) {


int dist[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
dist[i][j] = graph[i][j];
}
}

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


for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

printf("Shortest distances after iteration %d:\n", k+1);


//i++;
//if(i==n)
//{
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(dist[i][j] == INF) {
printf("%7s", "INF");
}
else {
printf("%7d",dist[i][j]);
}
}
printf("\n");
}
printf("\n");
//}
}
}

int main() {
int n;

printf("Enter the number of vertices: ");


scanf("%d", &n);

int **graph = (int **)malloc(n * sizeof(int *));


for(int i = 0; i < n; i++) {
graph[i] = (int *)malloc(n * sizeof(int));
}

printf("Enter the adjacency matrix:\n");


for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
if(graph[i][j] == -1) {
graph[i][j] = INF;
}
}
}

floyd_warshall(graph, n);
for(int i = 0; i < n; i++) {
free(graph[i]);
}
free(graph);

return 0;
}

Grahams Scan :-
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 100001
#define INF 987654321
using namespace std;
typedef long long lld;

struct Point
{
double X, Y;
Point()
{
this->X = this->Y = 0;
}
Point(double x, double y)
{
this->X = x;
this->Y = y;
}
};

int n;
Point P[MAX_N];
Point R;

inline bool cmp(Point A, Point B)


{
return atan2(A.Y-R.Y,A.X-R.X) < atan2(B.Y-R.Y,B.X-R.X);
}

inline double CCW(Point a, Point b, Point c)


{
return ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X));
}

inline int GrahamScan(vector<Point> &cH)


{
int min_id = 1;
for (int i=2;i<=n;i++)
{
if (P[i].Y < P[min_id].Y || (P[i].Y == P[min_id].Y && P[i].X < P[min_id].X))
{
min_id = i;
}
}
swap(P[1], P[min_id]);
R = P[1];
sort(P+2, P+n+1, cmp);

P[0] = P[n];
int HullSize = 1;

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


{
while (CCW(P[HullSize-1], P[HullSize], P[i]) <= 0)
{
if (HullSize > 1) HullSize--;
else if (i == n) break;
else i++;
}
swap(P[++HullSize], P[i]);
}

for (int i=1;i<=HullSize;i++) cH.push_back(P[i]);


return HullSize;
}

int main()
{
int i,a,b,p;
printf("enter the no of points:");
scanf("%d",&n);

for(int i=0;i<n;i++)
{
p=i+1;
scanf("%d %d",&a,&b);
P[p]=Point(a,b);

}
// P[1] = Point(-7, 8);
// P[2] = Point(-4, 6);
// P[3] = Point(2,6);
// P[4] = Point(6, 4);
// P[5] = Point(8, 6);
// P[6] = Point(7, -2);
// P[7] = Point(4,-6);
// P[8] = Point(8,-7);
// P[9] = Point(0, 0);
// P[10] = Point(3, -2);
// P[11] = Point(6,-10);
// P[12] = Point(0, -6);
// P[13] = Point(-9, -5);
// P[14] = Point(-8, -2);
// P[15] = Point(-8,0);
// P[16] = Point(-10,3);
// P[17] = Point(-2, 2);
// P[18] = Point(-10,4);
//P[16] = Point(-10,3);

vector<Point> cH;
int m = GrahamScan(cH);

printf("Hull size: %d\n",m);


for (int i=0;i<m;i++)
{
printf("%lf %lf\n",cH[i].X, cH[i].Y);
}

return 0;
}

Randomized Quick Sort :- ©


#include <time.h>
#include<stdio.h>
#include<stdlib.h>

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


int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j <= high - 1; j++) {


if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}

swap(&arr[i+1], &arr[high]);
return i+1;
}

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


srand(time(NULL));
int random = low + rand() % (high - low);
swap(&arr[random], &arr[high]);
return partition(arr, low, high);
}

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


if (low < high) {
int pivot = randomPartition(arr, low, high);
quicksort(arr, low, pivot-1);
quicksort(arr, pivot+1, high);
}
}
int main() {
int n;
printf("enter the no of values in the array:");
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

quicksort(arr, 0, n-1);

printf("\nSorted array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Bellman Ford Algorithm :-


#include<stdio.h>
#include<limits.h>
#define INF INT_MAX
#define N 6

char ch[] = {'A','B','C','D','E','F'};

struct Table
{
int d, pi;
}V[N];

void init(int s)
{
for (int v = 0; v<N; v++)
{
V[v].d = INF;
V[v].pi = -1;
}
V[s].d = 0;
}

void relax(int u, int v, int w)


{
if (V[v].d> (V[u].d + w))
{
V[v].d = V[u].d + w;
V[v].pi = u;
}
}
void bellmanFord(int G[N][N], int s)
{
init(s);

for (int i=1; i<=N-1; i++)


{
for (int u = 0; u<N; u++)
{
for (int v=0; v<N; v++)
{
if (G[u][v]!=0)
{
relax(u, v, G[u][v]);
}
}
}
}

int main()
{
int G[N][N] = {{0, 6, 4, 5, 0, 0},
{0, 0, 0, 0, -1, 0},
{0, -2, 0, 0, 3, 0},
{0, 0, -2, 0, 0, -1},
{0, 0, 0, 0, 0, 3},
{0, 0, 0, 0, 0, 0}};
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
scanf("%d",&G[i][j]);
}
}

int s = 0;

bellmanFord(G, s);

printf("\n Table values are :");

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


{
printf("\n %c \t %d \t %c", ch[v], V[v].d, ch[V[v].pi]);
}

Edmond Karp :-[1,2,3]


Code1 :-[sir]maxim
#include<stdio.h>
#include<limits.h>
#define INF INT_MAX
#define WHITE 0
#define GRAY 1
#define BLACK 2
#define N 6

char ch[] = {'s', 'A', 'B', 'C', 'D', 't'};

struct BFSTable
{
int color;
int d;
int pi;
}V[N];

struct Queue
{
int q[100];
int f;
int r;
}Q;

void initQueue()
{
Q.f = Q.r = -1;
}

void enqueue(int value)


{
Q.q[++Q.r] = value;
}

int isEmpty()
{
if ((Q.r == -1) || (Q.f == Q.r+1))
return 1;
else
return 0;
}

int dequeue()
{
if (!isEmpty())
{
return Q.q[Q.f++];
}
}

void init(int s)
{
for (int v=0; v<N; v++)
{
V[v].color = WHITE;
V[v].d = INF;
V[v].pi = -1;
}
V[s].d = 0;
V[s].pi = -1;
}

int bfs(int G[N][N], int s, int r[N][N], int t)


{
init(s);

V[s].color = GRAY;

enqueue(s);

while (!isEmpty())
{
int u;
u = dequeue();
for (int v=0; v<N; v++)
{
if (G[u][v]!=0)
{
if ((V[v].color==WHITE) && (r[u][v]>0))
{
if (v==t)
{
V[v].pi = u;
V[v].d = V[u].d+1;
return 1;
}
V[v].color=GRAY;
V[v].d = V[u].d + 1;
V[v].pi = u;
enqueue(v);
}

}
}

V[u].color = BLACK;
}
return 0;

int min(int a, int b)


{
if (a<b) return a;
else return b;
}

void edmondKarp(int G[N][N], int s, int t)


{
int r[N][N];

for (int u=0; u<N; u++)


for (int v=0; v<N; v++)
r[u][v] = G[u][v];

int mf = 0;
while (bfs(G, s, r, t))
{
int bnc = INF;
printTable();
printf("\n");
for (int v=t; v!=s; v=V[v].pi)
{
int u = V[v].pi;
bnc = min(bnc, r[u][v]);
}

mf = mf + bnc;

for (int v=t; v!=s; v=V[v].pi)


{
int u = V[u].pi;
r[u][v] = r[u][v]-bnc;
}
printf("\n Maxflow is : %d",mf);
}
}

void printTable()
{
printf("\n BFS Table is : \n");
printf("\n Node \t CLR \t DIST \t PI \n");
printf("------------------------------------\n");

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


{
printf("\n %c \t %d \t %d \t %c",
ch[v], V[v].color, V[v].d, ch[V[v].pi]);
}
}
void printPath()
{
int t = 5;
int s = 0;

printf("\n Path from %c -> %c: ", ch[s], ch[t]);

for (int v = t; v!=-1; v = V[v].pi)


{
printf("%c <- ",ch[v]);
}
}

void main()
{
int G[N][N] = {{0, 7, 0, 0, 4, 0},
{0, 0, 5, 3, 0, 0},
{0, 0, 0, 0, 0, 8},
{0, 0, 3, 0, 0, 5},
{0, 3, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 0}};
int s;
int t;
s = 0;
t = 5;
edmondKarp(G, s, t);

//printTable();
//printPath();
}

Code 2:- Edmond karp[musk]aa


#include<iostream>
#include<queue>
#include<cstring>
#include<limits.h>
using namespace std;
#define N 9
bool bfs(int rgraph[N][N],int s,int t,int parent[])
{
bool visited[N];
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<N;v++)
{
if(visited[v]==false && rgraph[u][v]>0)
{
q.push(v);
parent[v]=u;
visited[v]=true;
}
}
}
return visited[t]==true;
}
int edmondKarp(int G[N][N],int s,int t)
{
int u,v;
int rgraph[N][N];
for(int u=0;u<N;u++)
{
for(int v=0;v<N;v++)
{
rgraph[u][v]=G[u][v];
}
}
int parent[N];
int maxflow=0;
while(bfs(rgraph,s,t,parent))
{
int pathflow=INT_MAX;
for(v=t;v!=s;v=parent[v])
{
u=parent[v];
pathflow=min(pathflow,rgraph[u][v]);
}
for(v=t;v!=s;v=parent[v])
{
u=parent[v];
rgraph[u][v]-=pathflow;
rgraph[v][u]+=pathflow;
}
maxflow+=pathflow;
}
return maxflow;
}
bool DFS(int rGraph[N][N],int parent[],bool visited[],int n,int x,int t)
{
if(x == t)
return true;
visited[x] = true;
for(int i=0;i<n;++i)
{
if(rGraph[x][i]>0 && !visited[i])
{
parent[i]=x;
if(DFS(rGraph, parent, visited, n, i, t))
return true;
}
}
return false;
}
int fordFulkerson(int G[N][N],int n,int s,int t)
{
int u,v;
int rgraph[N][N];
for(int u=0;u<N;u++)
{
for(int v=0;v<N;v++)
{
rgraph[u][v]=G[u][v];
}
}
int parent[N];
int maxflow=0;
bool visited[N];
while(DFS(rgraph,parent,visited,n,s,t))
{
memset(visited,false,sizeof(visited));
int pathflow=INT_MAX;
for(v=t;v!=s;v=parent[v])
{
u=parent[v];
pathflow=min(pathflow,rgraph[u][v]);
}
for(v=t;v!=s;v=parent[v])
{
u=parent[v];
rgraph[u][v]-=pathflow;
rgraph[v][u]+=pathflow;
}
maxflow+=pathflow;
}
return maxflow;
}
int main()
{
int G1[9][9]={{0,26,17,0,37,0,0,0,0},
{0,0,0,20,10,0,0,0,0},
{0,0,0,0,20,15,0,0,},
{0,0,0,0,0,10,22,18,0},
{0,0,0,35,0,15,0,0,0},
{0,0,0,0,0,0,0,34,0},
{0,0,0,0,0,0,0,0,48},
{0,0,0,0,0,0,20,0,30},
{0,0,0,0,0,0,0,0,0}};
int G2[9][9]={{0,5,0,5,0,0,0,0,0},
{0,0,3,0,3,0,0,0,0},
{0,0,0,0,0,4,0,0,0},
{0,0,2,0,0,4,0,0,0},
{0,0,0,0,0,0,6,0,0},
{0,0,0,0,0,0,6,0,0},
{0,0,0,0,0,0,0,5,0},
{0,0,0,0,0,0,0,3,3},
{0,0,0,0,0,0,0,0,5}};
int G3[9][9]={{0,9,1,0,10,0,0,0,6},
{0,0,5,3,4,0,0,7,0},
{0,0,0,10,0,0,0,0,0},
{0,4,7,0,5,0,0,0,0},
{0,4,0,10,0,0,0,0,7},
{0,0,5,0,0,0,9,1,0},
{0,1,0,4,0,0,0,5,0},
{0,1,6,1,5,0,0,0,5},
{0,0,0,0,0,0,0,0,0}};
cout<<"Ford Fulkerson ";
cout<<fordFulkerson(G1,9,0,8)<<"\t"<<fordFulkerson(G2,9,0,8)<<"\
t"<<fordFulkerson(G3,9,0,8);
cout<<"\nEdmond Karp"<<"\t";
cout<<edmondKarp(G1,0,8)<<"\t"<<edmondKarp(G2,0,8)<<"\t"<<edmondKarp(G3,0,8);
}

Code 3:- gptttttttttaaaaa[path also]


#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

#define MAX_VERTICES 100

int graph[MAX_VERTICES][MAX_VERTICES];
int residual[MAX_VERTICES][MAX_VERTICES];
int parent[MAX_VERTICES];
int flow[MAX_VERTICES];
bool visited[MAX_VERTICES];

int n; // Number of vertices

// Find an augmenting path in the residual graph using BFS


bool bfs(int s, int t) {
int queue[MAX_VERTICES];
int front = 0, rear = 0;
for (int i = 0; i < n; i++) {
parent[i] = -1;
visited[i] = false;
}
visited[s] = true;
flow[s] = INT_MAX;
queue[rear++] = s;
while (front < rear) {
int u = queue[front++];
for (int v = 0; v < n; v++) {
if (!visited[v] && residual[u][v] > 0) {
parent[v] = u;
flow[v] = (flow[u] < residual[u][v]) ? flow[u] : residual[u][v];
if (v == t) {
return true;
}
visited[v] = true;
queue[rear++] = v;
}
}
}
return false;
}

// Run the Edmonds-Karp algorithm on the input graph


int edmonds_karp(int s, int t) {
int max_flow = 0;
for (int u = 0; u < n; u++) {
for (int v = 0; v < n; v++) {
residual[u][v] = graph[u][v];
}
}
while (bfs(s, t)) {
int path_flow = flow[t];
for (int v = t; v != s; v = parent[v]) {
int u = parent[v];
residual[u][v] -= path_flow;
residual[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}

int main() {
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix of the graph:\n");
for (int u = 0; u < n; u++) {
for (int v = 0; v < n; v++) {
scanf("%d", &graph[u][v]);
}
}
int s = 0, t = n-1; // Source and sink vertices
int max_flow = edmonds_karp(s, t);
printf("Maximum flow = %d\n", max_flow);
printf("Path of vertices with maximum flow: ");
int u = s;
while (u != t) {
for (int v = 0; v < n; v++) {
if (residual[u][v] < graph[u][v]) {
printf("%d ", u+1);
u = v;
break;
}
}
}
printf("%d\n", t+1);
return 0;
}

Fractional Knapsack :-
#include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity)
{
float x[20], tp = 0;
int i, j, u;
u = capacity;

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


x[i] = 0.0;

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


if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}

if (i < n)
x[i] = u / weight[i];

tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);

printf("\nMaximum profit is:- %f", tp);

int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &num);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}

printf("\nEnter the capacity of knapsack:- ");


scanf("%f", &capacity);

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


ratio[i] = profit[i] / weight[i];
}

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


for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}

knapsack(num, weight, profit, capacity);


return(0);
}

Naive algorithm :-
Code :-
#include<iostream>
#include<string.h>
using namespace std;

void search(char* pat, char* txt)


{
int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;

if (j== M)
cout << "The match is found: " << i+1 <<" - "<<i+j<< endl;
}
}
int main()
{
char txt[100] ;
char pat[100] ;
cin>>txt>>pat;

search(pat, txt);
return 0;
}

Rabin Karp :-
#include<iostream>

using namespace std;

#include <string.h>

#define d 10

void rabinKarp(char pattern[], char text[], int q) {

int m = strlen(pattern);

int n = strlen(text);
int i, j;

int p = 0;

int t = 0;

int h = 1;

for (i = 0; i < m - 1; i++)

h = (h * d) % q;

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

p = (d * p + pattern[i]) % q;

t = (d * t + text[i]) % q;

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

if (p == t) {

for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j])

break;

if (j == m)

printf("Pattern is found at position: %d \n", i + 1);

if (i < n - m) {

t = (d * (t - text[i] * h) + text[i + m]) % q;

if (t < 0)

t = (t + q);

}
}

int main() {

char text[100];

char pattern[100];

cin>>text>>pattern;

int q = 13;

rabinKarp(pattern, text, q);

Job Selection Problem :-


#include <stdio.h>
#include <stdlib.h>

#define MJ 100
#define MT 100

struct J {
int p;
int d;
int t;
};

int max(int x, int y) {


if (x > y) {
return x;
} else {
return y;
}
}
int cmpfunc(const void* a, const void* b) {
return ((struct J*)b)->p - ((struct J*)a)->p;
}

int fm(int a, int b) {


if (a < b) {
return a;
} else {
return b;
}
}

int main() {
struct J JOBS[MJ];
int n, i, j, tp = 0;

//printf("Enter the number of JOBSs: ");


// scanf("%d", &n);
n=4;
int p[4]={5,10,6,3};
int d[4]={1,3,2,1};
int t[4]={1,2,1,1};
/*

profit={5,10,6,3}

deadline={1,3,2,1}

time = {1,2,1,1}

*/
for (i = 0; i < n; i++) {
JOBS[i].p=p[i];
}
for (i = 0; i < n; i++) {
JOBS[i].d=d[i];
}
for (i = 0; i < n; i++) {
JOBS[i].t=t[i];
}

qsort(JOBS, n, sizeof(struct J), cmpfunc);

int s[MT] = {0};


for (i = 0; i < n; i++) {
int current_slot = fm(JOBS[i].d-2, MT - JOBS[i].t);
for (j = current_slot; j >= 0; j--) {
if (s[j] == 0) {
s[j] = 1;
tp += JOBS[i].p;
break;
}
}
}

printf("max profit=%d",tp);

return 0;
}

Karatsuba Faster Multiplication (n^1.59):-


#include<iostream>
#include<stdio.h>

using namespace std;

int makeEqualLength(string &str1, string &str2)


{
int len1 = str1.size();
int len2 = str2.size();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
str1 = '0' + str1;
return len2;
}
else if (len1 > len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
str2 = '0' + str2;
}
return len1; // If len1 >= len2
}

string addBitStrings( string first, string second )


{
string result;

int length = makeEqualLength(first, second);


int carry = 0;
for (int i = length-1 ; i >= 0 ; i--)
{
int firstBit = first.at(i) - '0';
int secondBit = second.at(i) - '0';

int sum = (firstBit ^ secondBit ^ carry)+'0';

result = (char)sum + result;

carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry);


}
if (carry) result = '1' + result;

return result;
}

int multiplyiSingleBit(string a, string b)


{ return (a[0] - '0')*(b[0] - '0'); }

long int multiply(string X, string Y)


{

int n = makeEqualLength(X, Y);

// Base cases
if (n == 0) return 0;
if (n == 1) return multiplyiSingleBit(X, Y);
int fh = n/2;
int sh = (n-fh);

string Xl = X.substr(0, fh);


string Xr = X.substr(fh, sh);

string Yl = Y.substr(0, fh);


string Yr = Y.substr(fh, sh);

long int P1 = multiply(Xl, Yl);


long int P2 = multiply(Xr, Yr);
long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr));

return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1<<sh) + P2;


}

int main()
{
printf ("%ld\n", multiply("1100", "1010"));
printf ("%ld\n", multiply("110", "1010"));
printf ("%ld\n", multiply("11", "1010"));
printf ("%ld\n", multiply("1", "1010"));
printf ("%ld\n", multiply("0", "1010"));
printf ("%ld\n", multiply("111", "111"));
printf ("%ld\n", multiply("11", "11"));
}

You might also like