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

LABORATORY INSTRUCTION MANUAL

ANALYSIS AND DESIGN OF ALGORITHM

4th Semester

Department of Computer Science and Engineering

University Institute of Engineering and Technology

Panjab University, Chandigarh

SUBMITTED TO: SUBMITTED BY:

Ms. Seema Rani Prikshit Rana

BE/CSE(II)

UE173076
INDEX

Lab Name of Practical Remarks


No.
1. Introduction to Algorithm
2. DIVIDE AND CONQUER
 Binary Search
 Merge Sort
 Quick Sort
 Selection Sort
 MinMax
3. GREEDY ALGORITHM
 Activity Selection
 Knapsack
 Single Source shortest path
 Kruskal’s
 Prim’s
4. DYNAMIC PROGRAMMING
 Assembly Line
 Multistage
 All pairs shortest path
 longest common sub-sequence
 0/1 Knapsack
5 BACKTRACKING
 N-Queen’s
 Graph Coloring
ALGORITHM : An algorithm is a step by step method of solving a problem. It is commonly
used for data processing, calculation and other related computer and mathematical operations.
An algorithm is also used to manipulate data in various ways, such as inserting a new data item,
searching for a particular item or sorting an item.

TYPE OF ALGORITHM :

 DIVIDE AND CONQUER: Divide and Conquer is an algorithmic paradigm. A


typical Divide and Conquer algorithm solves a problem using following three steps.
1. Divide: Break the given problem into subproblems of same type.
2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers
Following are some standard algorithms that are Divide and Conquer algorithms
 Binary Search
 Quick Sort
 Merge Sort
 Closest Pair of Points
 Strassen’s Algorithm

 GREEDY ALGORITHM: A greedy algorithm is a simple, intuitive algorithm that is


used in optimization problems. The algorithm makes the optimal choice at each step as it
attempts to find the overall optimal way to solve the entire problem. Greedy algorithms
are quite successful in some problems, such as Huffman encoding which is used to
compress data, or Dijkstra's algorithm, which is used to find the shortest path through a
graph.

 DYNAMIC PROGRAMMING: Dynamic Programming is a method for solving a


complex problem by breaking it down into a collection of simpler subproblems, solving
each of those subproblems just once, and storing their solutions using a memory-based
data structure (array, map,etc). Each of the subproblem solutions is indexed in some way,
typically based on the values of its input parameters, so as to facilitate its lookup. So the
next time the same subproblem occurs, instead of recomputing its solution, one simply
looks up the previously computed solution, thereby saving computation time. This
technique of storing solutions to subproblems instead of recomputing them is called
memoization.

 BACKTRACKING: Backtracking is an algorithmic-technique for solving problems


recursively by trying to build a solution incrementally, one piece at a time, removing those
solutions that fail to satisfy the constraints of the problem at any point of time.

There are three types of problems in backtracking –


1. Decision Problem – In this, we search for a feasible solution.
2. Optimization Problem – In this, we search for the best solution.
3. Enumeration Problem – In this, we find all feasible solutions.
DIVIDE AND CONQUER
 Write a program for binary search in C/C++.

//Binary Search
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class arrays{
public:
void input(int *&arr,int num);
void show_i(int *&arr,int num);
void search_b(int *&arr,int num);
};
void arrays::input(int *&arr,int num)
{ int i;
srand(time(0));
for(i=0; i<num; i++)
{ int r = rand() % num;
arr[i]=r;
}
}
void arrays::search_b(int *&arr,int num){
int a;
int first,last,middle;
cout<<"Enter the number that you want to search:\t";
cin>>a;
first = 0;
last = num-1;
middle = (first+last)/2;
while (first <= last) {
if(arr[middle] < a) {
first = middle + 1; }
else if(arr[middle] == a)
{
cout<<a<<" found in the array at the location "<<middle+1<<"\n";
break; }
else {
last = middle - 1; }
middle = (first + last)/2; }
if(first > last){
cout<<a<<" not found in the array"<<endl;
}}
void arrays::show_i(int *&arr,int num){
for(int i=0;i<num;i++)
cout<<arr[i]<<"\t";
}
int main(){
arrays a;
int num;
cout<<"Enter Size of Array"<<endl;
cin>>num;
int *arr=new int[num];
int o;
int start,stop;

do{ cout<<"\n1. Input\t 2.Binary Search \t 3. Show\t 4. Exit"<<endl;


cout<<"\nEnter Number"<<endl;
cin>>o;
switch(o){
case 1:
a.input(arr,num);
break;
case 2:
start = clock();
a.search_b(arr,num);
stop = clock();
cout<<"Time for binary search is : "<<(stop-start)/double(CLOCKS_PER_SEC)<<"
Seconds"<<endl;
break;
case 3:
a.show_i(arr,num);
break;
case 4:
return 0;
}
}
while(1);
delete [] arr;
}
OUTPUT
 Write a program for Merge Sort in C/C++.

//merge sort
#include <iostream>
#include<stdlib.h>
using namespace std;
class merge_sort{
public:
void merge_sort1(int[],int, int);
void merge_array(int[],int, int, int, int);
};
void merge_sort::merge_sort1(int arr_sort[],int i, int j) {
int m;

if (i < j) {
m = (i + j) / 2;
merge_sort1(arr_sort,i, m);
merge_sort1(arr_sort,m + 1, j);
merge_array(arr_sort,i, m, m + 1, j);
}
}
void merge_sort::merge_array(int arr_sort[],int a, int b, int c, int d) {
int t[d+1];
int i = a, j = c, k = 0;

while (i <= b && j <= d) {


if (arr_sort[i] < arr_sort[j])
t[k++] = arr_sort[i++];
else
t[k++] = arr_sort[j++];
}
while (i <= b)
t[k++] = arr_sort[i++];

while (j <= d)
t[k++] = arr_sort[j++];

for (i = a, j = 0; i <= d; i++, j++)


arr_sort[i] = t[j];
}
int main(){
merge_sort m;
int n,i,start,stop;
cout<<"Enter Size of array"<<endl;
cin>>n;
int *a=new int [n];
cout<<"Inserting "<<n<<" Random numbers"<<endl;
srand(time(0));
for(i=0; i<n; i++)
{
a[i]=rand()%n+1;
}
start = clock();
m.merge_sort1(a,0,n-1);
stop=clock();
cout<<"\nArray after sorting: "<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
cout<<"Time taken "<<(stop-start)/double(CLOCKS_PER_SEC)<<" Seconds"<<endl;
}

OUTPUT

Write a program for Quick Sort in C/C++.

//Quick Sort
#include <iostream>
using namespace std;
class quick_sort{
public:
void quick_sort1(int[],int,int);
int partition(int[],int,int);
};
void quick_sort::quick_sort1(int a[],int l,int u)
{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort1(a,l,j-1);
quick_sort1(a,j+1,u);
}
}
int quick_sort::partition(int a[],int p,int q){
int x,i,j,temp;
x=a[p];
i=p;
j=q+1;
do
{ do
i++;
while(a[i]<x&&i<=q);
do
j--;
while(x<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[p]=a[j];
a[j]=x;

return(j);
}
int main()
{ quick_sort q;
int n,i,start,stop,start1,stop1;
cout<<"Enter Size of array"<<endl;
cin>>n;
int *a=new int [n];
cout<<"Inserting "<<n<<" Random numbers"<<endl;
srand(time(0));
for(i=0; i<n; i++)
{
a[i]=rand()%n+1;
}
start = clock();
q.quick_sort1(a,0,n-1);
stop=clock();
cout<<"\nArray after sorting:"<<endl;
start1=clock();
for(i=0;i<n;i++){
cout<<a[i]<<" ";
cout<<"\t";}
stop1=clock();
cout<<"\nTime taken "<<(stop-start)/double(CLOCKS_PER_SEC)<<" Seconds"<<endl;
cout<<"Time taken "<<(stop1-start1)/double(CLOCKS_PER_SEC)<<" Seconds"<<endl;
return 0;
}

OUTPUT:

Write a program for Iterative Binary Search and Selection Sort in C/C++.

//Binary Search Iterative


#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class arrays{
public:
void input(int *&arr,int num);
void sort_s(int *&arr,int num);
void search_b(int *&arr,int num);
void show_i(int *&arr,int num);
};
void arrays::input(int *&arr,int num)
{ int i;
srand(time(0));
for(i=0; i<num; i++)
{
arr[i]=rand()%num+1;
}}
void arrays::search_b(int *&arr,int num){
int a,first,last,middle;
cout<<"Enter the number that you want to search:\t";
cin>>a;
first = 0;
last = num-1;
middle = (first+last)/2;
while (first <= last) {
if(arr[middle] < a) {
first = middle + 1; }
else if(arr[middle] == a)
{
cout<<a<<" found in the array at the location "<<middle+1<<"\n";
break; }
else {
last = middle - 1; }
middle = (first + last)/2; }
if(first > last){
cout<<a<<" not found in the array"<<endl;
}}
void arrays::sort_s(int *&arr,int num)
{
int i,j,temp;
cout<<"Sorting array using selection sort\n";
for(i=0;i<num;i++) {
for(j=0;j<num-1;j++) {
if(arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}}}}
void arrays::show_i(int *&arr,int num){
for(int i=0;i<num;i++)
cout<<arr[i]<<"\t";
}
int main(){
arrays a;
int num;
cout<<"Enter Size of Array"<<endl;
cin>>num;
int *arr=new int[num];
int o;
int start,stop;

do{ cout<<"\n1. Input\t 2.Selection Sort \t 3.Binary Search \t 4.Show\t 5.Exit"<<endl;


cout<<"\nEnter Number"<<endl;
cin>>o;
switch(o){
case 1:
a.input(arr,num);
break;
case 2:
start = clock();
a.sort_s(arr,num);
stop=clock();
cout<<"Time for selection sorting is : "<<(stop-start)/double(CLOCKS_PER_SEC)<<"
Seconds"<<endl;
break;
case 3:
start = clock();
a.search_b(arr,num);
stop = clock();
cout<<"Time for binary search is : "<<(stop-start)/double(CLOCKS_PER_SEC)<<"
Seconds"<<endl;
break;
case 4:
a.show_i(arr,num);
break;
case 5:
return 0;
}
}
while(1);
delete [] arr;
}

OUTPUT:
 Write a program for Min and Max in C/C++.
//min_max
#include <iostream>
#include <climits>
using namespace std;

void findMinAndMax(int arr[], int low, int high, int& min, int& max)
{
if (low == high)
{
if (max < arr[low])
max = arr[low];

if (min > arr[high])


min = arr[high];

return;
}

if (high - low == 1)
{
if (arr[low] < arr[high])
{
if (min > arr[low])
min = arr[low];

if (max < arr[high])


max = arr[high];
}
else
{
if (min > arr[high])
min = arr[high];

if (max < arr[low])


max = arr[low];
}
return;
}

int mid = (low + high) / 2;

findMinAndMax(arr, low, mid, min, max);

findMinAndMax(arr, mid + 1, high, min, max);


}

int main()
{
int n;
cout<<"Enter Value of n"<<endl;
cin>>n;
int arr[n];
cout<<"Enter Data in Array"<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];

int max = INT_MIN, min = INT_MAX;

findMinAndMax(arr, 0, n - 1, min, max);

cout << "The minimum element in the array is " << min << '\n';
cout << "The maximum element in the array is " << max;

return 0;
}

OUTPUT:

GREEDY ALGORITHM
 Write a program for activity selection poroblem in C/C++.

//activity-selection
#include<iostream>
#include <algorithm>
using namespace std;
class activity
{
public:
float stime;
float ftime;
string name;
void insertinact(int t1,int t2,string n)
{
stime=t1;
ftime=t2;
name=n;
}
void display()
{
cout<<"Activity with name "<<name<<" is executed"<<endl;
cout<<endl;
}
};
bool gettime(activity a,activity b)
{
return (a.ftime<b.ftime);
}

/*bool gettime2(activity a,activity b)


{
return (a.stime<b.stime);
}*/
int main()
{
activity arr[5];
for(int i=0;i<5;i++)
{
int s,f;
string name;
cout<<"Enter the value to activity "<<i+1<<"(Start Time, End time, Name)"<<endl;
cin>>s;
cin>>f;
cin>>name;
arr[i].insertinact(s,f,name);
}
cout<<"Sorted according to Finish time"<<endl;
sort(arr,arr+5,gettime);
//cout<<endl;
//sort(arr,arr+5,gettime2);
arr[0].display();
for(int i=0;i<5;)
{
for(int j=i+1;j<=5;j++)
{
if(arr[i].stime==arr[j].stime)
{
int c1=arr[i].ftime-arr[i].stime;
int c2=arr[j].ftime-arr[j].stime;
if(c1>c2)
{
arr[j].display();
i=j;
break;
}

}
else if(arr[i].ftime<=arr[j].stime)
{
arr[j].display();
i=j;
break;

}
}
}
}

OUTPUT:
 Write a program for Knapsack poroblem in C/C++.

//knapsack
#include<iostream>

using namespace std;

int main()

int array[2][100], n, w, i, curw, used[100], maxi = -1, totalprofit = 0;

cout << "Enter number of objects: ";

cin >> n;

cout << "Enter the weight of the knapsack: ";

cin >> w;

cout<<"Enter Weight and profit of "<<n<<" Objects"<<endl;

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

{
cin >> array[0][i] >> array[1][i];
}

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

{
used[i] = 0;
}

curw = w;

while (curw >= 0)

{
maxi = -1;

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


{
if ((used[i] == 0) && ((maxi == -1) || (((float) array[1][i]

/ (float) array[0][i]) > ((float) array[1][maxi]

/ (float) array[0][maxi]))))

{
maxi = i;
}
}

used[maxi] = 1;

curw -= array[0][maxi];

totalprofit += array[1][maxi];

if (curw >= 0)
{
cout << "\nAdded object " << maxi + 1 << " Weight: "

<< array[0][maxi] << " Profit: " << array[1][maxi]

<< " completely in the bag, Space left: " << curw;
}

else

{
cout << "\nAdded object " << maxi + 1 << " Weight: "

<< (array[0][maxi] + curw) << " Profit: "

<< (array[1][maxi] / array[0][maxi]) * (array[0][maxi]

+ curw) << " partially in the bag, Space left: 0"

<< " Weight added is: " << curw + array[0][maxi];

totalprofit -= array[1][maxi];

totalprofit += ((array[1][maxi] / array[0][maxi]) * (array[0][maxi]

+ curw));
}

cout << "\nBags filled with objects worth: " << totalprofit;

return 0;

}
OUTPUT:

 Write a program for single source shortest path in C/C++.

//dijkstra
#include <cstdio>

#include <queue>

#include <vector>

#include <iostream>

using namespace std;

#define MAX 100001

#define INF (1<<20)

#define pii pair< int, int >

#define pb(x) push_back(x)

struct comp

{
bool operator()(const pii &a, const pii &b)

{
return a.second > b.second;
}
};

priority_queue<pii, vector<pii > , comp> Q;

vector<pii > G[MAX];

int D[MAX];

bool F[MAX];

int main()

int i, u, v, w, sz, nodes, edges, starting;

cout << "Enter the number of vertices and edges: ";

cin >> nodes >> edges;

cout << "Enter the edges with weigth: <source> <destination> <weigth>: \n";

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

{
cin >> u >> v >> w;

G[u].pb(pii(v, w));

G[v].pb(pii(u, w));

}
cout << "Enter the source node: ";

cin >> starting;

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

D[i] = INF;

D[starting] = 0;

Q.push(pii(starting, 0));

while (!Q.empty())

{
u = Q.top().first;

Q.pop();

if (F[u])

continue;

sz = G[u].size();

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

{
v = G[u][i].first;

w = G[u][i].second;

if (!F[v] && D[u] + w < D[v])

D[v] = D[u] + w;

Q.push(pii(v, D[v]));

}
}

F[u] = 1;

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

cout << "Node " << i << ", min weight = " << D[i] << endl;

return 0;

}
OUTPUT:

 Write
a

program for mimimum spanning tree (KRUSKAL) in C/C++.

#include <iostream>
using namespace std;
int i,j,k,a,b,u,v,n,ne=1;
int min_,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{
cout<<"\n\tImplementation of Kruskal's algorithm\n";
cout<<"\nEnter the no. of vertices: ";
cin>>n;
cout<<"\nEnter the cost adjacency matrix:\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;
}
}
cout<<"The edges of Minimum Cost Spanning Tree are\n";
while(ne < n)
{
for(i=1,min_=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min_)
{
min_=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
cout<<ne++ <<" edge "<<a<<","<<b<<" = "<<min_<<endl;
mincost +=min_;
}
cost[a][b]=cost[b][a]=999;
}
cout<<"\n\tMinimum cost = "<<mincost<<endl;
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

OUTPUT:
 Write a
program
for
mimimum spanning tree (PRISM) in C/C++.

#include<iostream>

using namespace std;

int weight[20][20],visited[20],d[20],p[20];
int v,e;

void creategraph()
{
int i,j,a,b,w;
cout<<"\nEnter number of vertices ";
cin>>v;
cout<<"\nEnter number of edges ";
cin>>e;
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
weight[i][j]=0;
for(i=1;i<=v;i++)
{
p[i]=visited[i]=0;
d[i]=32767;
}
for(i=1;i<=e;i++)
{
cout<<"\nEnter edge a,b and weight w:";
cin>>a>>b>>w;
weight[a][b]=weight[b][a]=w;
}
}

void prim()
{
int current,totalvisited,mincost,i;
current=1;d[current]=0;
totalvisited=1;
visited[current]=1;
while(totalvisited!=v)
{
for(i=1;i<=v;i++)
{
if(weight[current][i]!=0)
if(visited[i]==0)
if(d[i]>weight[current][i])
{
d[i]=weight[current][i];
p[i]=current;
}
}
mincost=32767;
for(i=1;i<=v;i++)
{
if(visited[i]==0)
if(d[i]<mincost)
{
mincost=d[i];
current=i;
}
}
visited[current]=1;
totalvisited++;
}
mincost=0;
for(i=1;i<=v;i++)
mincost+=d[i];
cout<<"\nMinimum cost="<<mincost;
cout<<"\nMinimum span tree is";
for(i=1;i<=v;i++)
cout<<"\nVertex "<<i<<" is connected to"<<p[i];
}

int main()
{
creategraph();
prim();
}

OUTPUT:
DYNAMIC PROGRAMMING

 Write a program for assembly-line scheduling in C/C++.

#include<iostream>

#include<vector>

using namespace std;

int assemblyLineScheduling(int n, vector<int> entry, vector<int> exit, vector<vector<int> >


processing, vector<vector<int> > transfer)

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

int i;

dp[0][0]=entry[0]+processing[0][0];

dp[1][0]=entry[1]+processing[1][0];

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

dp[0][i]=min(dp[0][i-1],dp[1][i-1]+transfer[1][i-1])+processing[0][i];

dp[1][i]=min(dp[1][i-1],dp[0][i-1]+transfer[0][i-1])+processing[1][i];

dp[0][n]=dp[0][n-1]+exit[0];

dp[1][n]=dp[1][n-1]+exit[1];

return min(dp[0][n],dp[1][n]);

int main()

{
int i,n;

vector<int> entry(2), exit(2);

cout<<"Enter the number of stations ";


cin>>n;

vector<vector<int> > processing(2, vector<int> (n));

vector<vector<int> > transfer(2, vector<int> (n-1));

cout<<"Enter the entry time for assebly line 1 and 2 respectively"<<endl;

cin>>entry[0]>>entry[1];

cout<<"Enter the exit time for assebly line 1 and 2 respectively"<<endl;

cin>>exit[0]>>exit[1];

cout<<"Entry the processing time at all staions on assembly line 1"<<endl;

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

cin>>processing[0][i];

cout<<"Entry the processing time at all staions on assembly line 2"<<endl;

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

cin>>processing[1][i];

cout<<"Enter the transfer time from each station of assembly line 1 to next station of assembly
line 2"<<endl;

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

cin>>transfer[0][i];

cout<<"Enter the transfer time from each station of assembly line 2 to next station of assembly
line 1"<<endl;

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

cin>>transfer[1][i];

cout<<"The minimum time required to get all the jobs done is "<<endl;

cout<<assemblyLineScheduling(n, entry, exit, processing, transfer);

cout<<endl;

return 0;

}
OUTPUT

 Write
a

program for Multi-Stage Graph in C/C++.

#include<iostream>
using namespace std;

struct fwd{
int l;
int a[20];
};

struct fwd s1[10];

int main(){

int k,i,j,n,p[10],m,z,cost[50],v,c[20][20];

cout<<"Enter the no. of stages :";

cin>>k;

n=0;
for(i=1;i<=k;i++){
cout<<"Enter no. of vertices in stage "<<i<<" :";

cin>>s1[i].l;

n+=s1[i].l;

for(j=1;j<=s1[i].l;j++){
cout<<"Enter the value of vertex "<<j<<" :";

cin>>s1[i].a[j];

}
}

for(i=1;i<k;i++)
{

for(j=s1[i].a[1];j<=s1[i].a[s1[i].l];j++)

{
for(z=s1[i+1].a[1];z<=s1[i+1].a[s1[i+1].l];z++)
{

cout<<"Enter the cost of c["<<j<<"]["<<z<<"] :";


cin>>c[j][z];

}
}
}

cost[n]=0;

int min,d[50],t;

for(i=k-1;i>=1;i--)
{

for(j=s1[i].a[1];j<=s1[i].a[s1[i].l];j++)
{

min=999;

for(z=s1[i+1].a[1];z<=s1[i+1].a[s1[i].l];z++){

if(cost[z]+c[j][z]<min)

min=cost[z]+c[j][z];

t=z;
}
cost[j]=min;
d[j]=t;

p[1]=1;

p[k]=n;

for(i=2;i<k;i++)

p[i]=d[p[i-1]];

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

cout<<p[i]<<"-->";

cout<<p[k];

OUTPUT
 Write a program for All Pair Shortest Path in C/C++.

#include<iostream>
#define inf 99999
using namespace std;

int main()
{

int cost[10][10],a[10][10];
int n,e,f,s;
int i,j,k,c;
cout<<"enter no. of nodes in graph \n";
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
cost[i][j]=0;
else
cost[i][j]=inf;
}
}
cout<<"enter no. of edges \n";
cin>>e;
for(k=1;k<=e;k++)
{
cout<<"for edge "<<k<<endl;
cout<<"enter first vertex : ";
cin>>f;
cout<<"enter second vertex :";
cin>>s;
cout<<"enter the cost : ";
cin>>c;
cost[f][s]=c;
cost[s][f]=c;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=cost[i][j];
}
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=min(a[i][j], a[i][k]+a[k][j]);
}
}
}
cout<<"shortest distance matrix \n";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
} cout<<endl;
}
}

OUTPUT
 Write a program for Longest Common Subsequence in C/C++.

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

int i,j,m,n,c[20][20];
char x[20],y[20],b[20][20];

void print(int i,int j)


{
if(i==0 || j==0)
return;
if(b[i][j]=='c')
{
print(i-1,j-1);
cout<<x[i-1];
}
else if(b[i][j]=='u')
print(i-1,j);
else
print(i,j-1);
}

void lcs()
{
m=strlen(x);
n=strlen(y);
for(i=0;i<=m;i++)
c[i][0]=0;
for(i=0;i<=n;i++)
c[0][i]=0;
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
{
if(x[i-1]==y[j-1])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]='c';
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]='u';
}
else
{
c[i][j]=c[i][j-1];
b[i][j]='l';
}
}
}
int main()
{
cout<<"Enter 1st sequence:";
cin>>x;
cout<<"Enter 2nd sequence:";
cin>>y;
cout<<"\nThe Longest Common Subsequence is ";
lcs();
print(m,n);
return 0;
}

OUTPUT
 Write a program for 0/1 Knapsack in C/C++.

#include<iostream>
using namespace std;

int max(int a, int b) {


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

int knapsack(int W, int w[], int V[], int n)


{
int i, j;
int T[n+1][W+1];

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


{
for (j = 0; j <= W; j++)
{
if (i==0 || j==0)
T[i][j] = 0;
else if (w[i-1] <= j)
T[i][j] = max(V[i-1] + T[i-1][j-w[i-1]], T[i-1][j]);
else
T[i][j] = T[i-1][j];
}
}

printf("DP table T[i,j] : \n");


for(i=0;i<=n;i++)
{
cout<<"i= "<<i<<"\t";
for(j=0;j<=W;j++)
{
cout<<T[i][j]<<"\t";
}
cout<<endl;
}
cout<<endl;

return T[n][W];
}

int main()
{ int n;
cout<<"Total Number of items"<<endl;
cin>>n;
int w[n];
int V[n];
cout<<"Enter weight of Item"<<endl;
for(int i=0;i<n;i++)
cin>>w[i];
cout<<"Enter value of Item"<<endl;
for(int i=0;i<n;i++)
cin>>V[i];
//int w[n] = {5, 4, 6, 3};
//int V[n] = {10, 40, 30, 50};
int W = 10;
int Max;

printf("Details of all items : \n");


printf("Value\\Profit\tWeight\t\n");
for (int i = 0; i < n; i++)
{
cout<<V[i]<<"\t"<<w[i]<<endl;
}

cout<<endl;
Max = knapsack(W, w, V, n);
cout<<"Maximum profit we can obtain = "<<Max;
return 0;
}

OUTPUT
BACKTRACKING

 Write a program for N-Queen’s in C/C++.

#include <iostream>

#include <cstdio>

#include <cstdlib>

#define N 5

using namespace std;

void printSolution(int board[N][N])

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

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

cout<<board[i][j]<<" ";

cout<<endl;

bool isSafe(int board[N][N], int row, int col)

int i, j;

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

if (board[row][i])

return false;

}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)

if (board[i][j])

return false;

for (i = row, j = col; j >= 0 && i < N; i++, j--)

if (board[i][j])

return false;

return true;

bool solveNQUtil(int board[N][N], int col)

if (col >= N)

return true;

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

if ( isSafe(board, i, col) )

board[i][col] = 1;

if (solveNQUtil(board, col + 1) == true)

return true;

board[i][col] = 0;

}
return false;

bool solveNQ()

int board[N][N] = {0};

if (solveNQUtil(board, 0) == false)

cout<<"Solution does not exist"<<endl;

return false;

printSolution(board);

return true;

int main()

solveNQ();

return 0;

OUTPUT
 Write a program for graph coloring in C/C++.

#include<iostream>
using namespace std;
int G[10][10],m,edges,color_tab[10],v1,v2,i,j,n,a,b;
void Gen_Col_Value(int,int);
void Gr_coloring(int,int);
int main()
{
cout<<"\nEnter the number of nodes & edges\n";
cin>>n>>edges;
m=n-1;
cout<<"\nEnter the edges of the graph\n\n";
for (i=1;i<=edges; i++)
{
cout<<"Enter value of x,y\n";
cin>>v1>>v2;
G[v1][v2] = G[v2][v1] = 1;
cout<<endl;
}
Gr_coloring(1,n);
cout<<"\n The Vertices To be Coloured As...\n";
for(i=1;i<=n;i++)
cout<<"\n V"<<i<<":= "<<color_tab[i];
return 0;
}
void Gen_Col_Value(int k,int n)
{
while(1)
{
a=color_tab[k]+1;
b=m+1;
color_tab[k] = a%b;
if(color_tab[k]==0) return;
for(j=1;j<=n;j++)
{
if(G[k][j] && color_tab[k]==color_tab[j])
break;
}
if(j==n+1) return;
}
}
void Gr_coloring(int k,int n)
{
Gen_Col_Value(k,n);
if(color_tab[k]==0) return;
if(k==n) return;
else Gr_coloring(k+1,n);
}
OUTPUT

You might also like