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

ADSA file

This document is a practical file for the Advanced Data Structure and Algorithms course at Indira Gandhi Delhi Technical University for Women. It contains various programming tasks, including reversing a circular linked list, implementing a queue using two stacks, operations in a binary search tree, counting inversions, activity selection, finding k-clusters using Prim's algorithm, subset sum, 0/1 knapsack, sequence alignment, and knapsack using branch and bound. Each task includes code snippets and explanations for implementation.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ADSA file

This document is a practical file for the Advanced Data Structure and Algorithms course at Indira Gandhi Delhi Technical University for Women. It contains various programming tasks, including reversing a circular linked list, implementing a queue using two stacks, operations in a binary search tree, counting inversions, activity selection, finding k-clusters using Prim's algorithm, subset sum, 0/1 knapsack, sequence alignment, and knapsack using branch and bound. Each task includes code snippets and explanations for implementation.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

INDIRA GANDHI DELHI

TECHNICAL UNIVERSITY FOR WOMEN

Advanced Data Structure and Algorithms


PRACTICAL FILE
Subject Code: BIT-308
Bachelor of Technology- (Information Technology)
SEMESTER – 6th
PROGRAM AND BRANCH : B.Tech IT (3rd Year)

SUBMITTED BY : SHREYA SINGH SUBMITTED TO : DR. SHWETA JINDAL

ENROLLMENT NO. : 06201032022 ( H Group) Assistant Prof. (IT)


Index

1.(i) Write a program to reverse a Circular Linked List.


Code:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data){
this->data=data;
this->next=NULL;
}
};

void reverseCLL(Node* &head){


Node*oriHead=head;
Node* prev=NULL;
Node* curr=head;

if(head==NULL){
cout<<"Empty list , Reversal not possible!!";
}
Node* nn=curr->next;
while(nn!=head){
curr->next=prev;
prev=curr;
curr=nn;
nn=nn->next;
}
curr->next=prev;
head=curr;
oriHead->next=head;
}
void printll(Node* &head){
Node* temp=head;
do{
cout << temp->data << " ";
temp=temp->next;
}
while(temp!=head);
cout<<endl;
}

int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next=head;
cout<<"Original List is : ";
printll(head);
reverseCLL(head);
cout<<"Reversed list is: ";
printll(head);

return 0;
}

OUTPUT:

1.(ii) Write a program to implement a queue using two stacks.


Code:
#include<bits/stdc++.h>
#include <iostream>
#include<stack>
using namespace std;
class Queue{
public:
stack<int> s1;
stack <int>s2;
void enqueue(int data){
s1.push(data);
}

int dequeue(){
while(!s1.empty()){
int x=s1.top();
s1.pop();
s2.push(x);
}
int deleted=s2.top();
s2.pop();
while(!s2.empty()){
int y=s2.top();
s2.pop();
s1.push(y);
}
return deleted;

}
void printQ(stack<int>s1){
while(!s1.empty()){
cout<<s1.top()<<" ";
s1.pop();
}
}};
int main() {
Queue Q;
Q.enqueue(100);
Q.enqueue(200);
Q.enqueue(300);
Q.enqueue(400);
Q.enqueue(500);
cout<<"This is stack view of Queue!!"<<endl;
cout<<"The queue is : ";
Q.printQ(Q.s1);
cout<<endl;
cout<<"Deleted element is : "<<Q.dequeue()<<endl;
cout<<"Deleted element is : "<<Q.dequeue()<<endl;
cout<<"Queue after deletion is : ";
Q.printQ(Q.s1);
return 0;
}

2. Implement operations in Binary Search Tree.


Code:
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node*left,*right;
Node(int val){
data=val;
left=right=NULL;
}
};
Node *insert(Node* root,int ele){
if(!root){
Node*temp=new Node(ele);
return temp;

}
if(ele<root->data){
root->left=insert(root->left,ele);
}
else{
root->right=insert(root->right,ele);
}
return root;
}
void inorder(Node*root){
if(!root) return ;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);

int main() {
int input[]={1,4,2,5,8,12,10,11,6,9};
Node * root=NULL;
for(int i=0;i<10;i++){
root=insert(root,input[i]);
}
cout<<"The (inorder traversal) of tree after insertion is : ";
inorder(root);

3.(i) Counting number of inversions using divide and conquer strategy.


Code:
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int merge(vector<int>&arr,int l,int mid,int hi){
vector<int>temp;
int left=l;
int right=mid+1;
int cnt=0;
while(left<=mid&&right<=hi){
if(arr[left]<=arr[right]){
temp.push_back(arr[left]);
left++;
}
else {
temp.push_back(arr[right]);
cnt += (mid - left + 1);
right++;
}}
while(left<=mid){
temp.push_back(arr[left]);
left++;
}
while(right<=hi){
temp.push_back(arr[right]);
right++;
}
for(int i=l;i<=hi;i++){
arr[i]=temp[i-l];
}
return cnt;
}
int mergeSort(vector<int> &arr,int l,int h){
int cnt=0;
if(l>=h) return cnt;
int mid=(l+h)/2;
cnt+=mergeSort(arr,l,mid);
cnt+=mergeSort(arr,mid+1,h);
cnt+=merge(arr,l,mid,h);
return cnt;
}
int NoOfInversion(vector<int>&arr,int size){
return mergeSort(arr,0,size-1);
}
int main() {
vector<int>arr={5,4,3,2,1,9,10,7};
int size=8;
int count=NoOfInversion(arr,size);
cout<<"The number of inversions are :"<<count<<endl;
return 0;
}
3.(ii) Activity selection using greedy strategy.

Code:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;

void ActSelection(int start[],int finish[],int size){


vector<pair<int,int>>activity;
for(int i=0;i<size;i++){
activity.push_back({finish[i],start[i]});
}
sort(activity.begin(),activity.end());
cout<<"Selected non-conflicting activities are: "<<endl;

int selected=activity[0].first;
cout<<"("<<activity[0].second<<","<<activity[0].first<<")";

for(int i=1;i<size;i++){
if(activity[i].second>=selected){
cout<<"("<<activity[i].second<<","<<activity[i].first<<")";
selected=activity[i].first;
}
}
}
int main() {
int start[]={1,2,5,6,0,4};
int finish[]={2,4,7,6,8,9};
int size=sizeof(start)/sizeof(start[0]);
ActSelection(start,finish,size);
}

3.(iii).Find k- clusters in a graph using prim’s algorithm.


Code:
#include <iostream>
using namespace std;
const int INF = 1e9;
const int MAX = 100;
int graph[MAX][MAX];
bool visited[MAX];
int parent[MAX];
int cost[MAX];
int V, E;
void primsAlgo() {
for (int i = 0; i < V; i++) {
cost[i] = INF;
visited[i] = false;
parent[i] = -1;
}
cost[0] = 0;
for (int i = 0; i < V - 1; i++) {
int u = -1;
for (int j = 0; j < V; j++) {
if (!visited[j] && (u == -1 || cost[j] < cost[u]))
u = j;}
visited[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] && !visited[v] && graph[u][v] < cost[v]) {
cost[v] = graph[u][v];
parent[v] = u;
}}}}

void kClusters(int k) {
int edges[MAX][3];
int edgeCount = 0;
for (int i = 1; i < V; i++) {
edges[edgeCount][0] = parent[i];
edges[edgeCount][1] = i;
edges[edgeCount][2] = graph[parent[i]][i];
edgeCount++;
}
for (int i = 0; i < edgeCount - 1; i++) {
for (int j = 0; j < edgeCount - i - 1; j++) {
if (edges[j][2] < edges[j + 1][2]) {
swap(edges[j], edges[j + 1]);
}}}
cout << k << " clusters formed using edges:\n";
for (int i = k - 1; i < edgeCount; i++) {
cout << edges[i][0] << " - " << edges[i][1]
<< " (weight: " << edges[i][2] << ")\n";
}}
int main() {
V = 6;
E = 7;
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = 0;

int inputEdges[7][3] = {
{0, 1, 4}, {0, 2, 3}, {1, 2, 1},
{1, 3, 2}, {2, 3, 4}, {3, 4, 2},
{4, 5, 6}
};

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


int u = inputEdges[i][0];
int v = inputEdges[i][1];
int w = inputEdges[i][2];
graph[u][v] = w;
graph[v][u] = w;
}

primsAlgo();
int k = 3;
kClusters(k);

return 0;
}

Output:

4.(i).Subset Sum using backtracking and DP.


Code:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
bool SubsetSum(vector<int>&subset,int n,int sum){
if (sum==0) return true;
if(n==0) return false;
if(subset[n-1]>sum){
return SubsetSum(subset,n-1,sum);
}
return SubsetSum(subset,n-1,sum)||SubsetSum(subset,n-1,sum-subset[n-
1]);
}
int main() {
vector<int>subset={1,8,5,2,4,3};
int sum=6;
int n=subset.size();
if(SubsetSum(subset,n,sum)){
cout<<"Yes, there exists subsets with given sum !"<<endl;
}
else{
cout<<"No , there doesn't exists subsets with give sum! "<<endl;
}
return 0;
}
4.(ii). 0/1 knapsack using Greedy, DP and Backtracking.
Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int knapsackDP(int C, vector<int>& wt, vector<int>& val, int n) {
vector<vector<int>> dp(n+1, vector<int>(C+1, 0));

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


for (int w = 0; w <= C; w++) {
if (wt[i-1] <= w)
dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt[i-1]] + val[i-1]);
else
dp[i][w] = dp[i-1][w];
}
}

return dp[n][C];
}

int main() {
vector<int> wt = {15, 10, 50};
vector<int> val = {80, 50, 200};
int C = 50;
int n = wt.size();

cout << "Max value that can be made using DP is : " << knapsackDP(C,
wt, val, n) << endl;
return 0;
}
5(i). Perform Sequence Alignment.
Code:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
const int match = 1;
const int mismatch_penalty = -1;
const int gap = -2;
int maximum(int a, int b, int c) {
return max(a, max(b, c));
}
void SequenceAlignment(string seq1, string seq2) {
int x = seq1.length();
int y = seq2.length();
vector<vector<int>> cost(x + 1, vector<int>(y + 1));
vector<vector<char>> direction(x + 1, vector<char>(y + 1));
for (int i = 0; i <= x; i++) {
cost[i][0] = i * gap;
direction[i][0] = 'u'; }
for (int j = 0; j <= y; j++) {
cost[0][j] = j * gap;
direction[0][j] = 'l';
}
direction[0][0] = '0';
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
int matchedcost = (seq1[i - 1] == seq2[j - 1]) ? match :
mismatch_penalty;
int diagonal = cost[i - 1][j - 1] + matchedcost;
int up = cost[i - 1][j] + gap;
int left = cost[i][j - 1] + gap;
cost[i][j] = maximum(diagonal, up, left);
if (cost[i][j] == diagonal) direction[i][j] = 'D';
else if (cost[i][j] == up) direction[i][j] = 'u';
else direction[i][j] = 'l';
}}
int i = x, j = y;
string aligned1 = "", aligned2 = "";
while (i > 0 || j > 0) {
if (direction[i][j] == 'D') {
aligned1 = seq1[i - 1] + aligned1;
aligned2 = seq2[j - 1] + aligned2;
i--, j--;
} else if (direction[i][j] == 'u') {
aligned1 = seq1[i - 1] + aligned1;
aligned2 = '-' + aligned2;
i--;
} else if (direction[i][j] == 'l') {
aligned1 = '-' + aligned1;
aligned2 = seq2[j - 1] + aligned2;
j--; }}
cout << "Sequence 1: " << aligned1 << endl;
cout << "Sequence 2: " << aligned2 << endl;
cout << "Alignment Cost: " << cost[x][y] << endl;
}
int main() {
string seq1 = "TEMPLE";
string seq2 = "TEMPER";
SequenceAlignment(seq1, seq2);
return 0;
}
Output:
5(ii). 0/1 Knapsack using Branch and Bound.
Code:
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct Item {
int weight, profit;
float ratio;
};
struct Node {
int level, profit, weight;
float bound; };
bool compare(Item a, Item b) {
return a.ratio > b.ratio;
}
float calculateBound(Node u, int n, int W, Item items[]) {
if (u.weight >= W) return 0;
float profit_bound = u.profit;
int j = u.level + 1;
int totalWeight = u.weight;
while (j < n && totalWeight + items[j].weight <= W) {
totalWeight += items[j].weight;
profit_bound += items[j].profit;
j++;
}
if (j < n)
profit_bound += (W - totalWeight) * items[j].ratio;
return profit_bound;
}
int knapsack(Item items[], int n, int W) {
sort(items, items + n, compare);
queue<Node> q;
Node u, v;
u.level = -1; u.profit = 0; u.weight = 0;
u.bound = calculateBound(u, n, W, items);
q.push(u);
int maxProfit = 0;
while (!q.empty()) {
u = q.front(); q.pop();
if (u.level == n - 1) continue;
v.level = u.level + 1;
v.weight = u.weight + items[v.level].weight;
v.profit = u.profit + items[v.level].profit;
if (v.weight <= W && v.profit > maxProfit)
maxProfit = v.profit;
v.bound = calculateBound(v, n, W, items);
if (v.bound > maxProfit)
q.push(v);
v.weight = u.weight;
v.profit = u.profit;
v.bound = calculateBound(v, n, W, items);
if (v.bound > maxProfit)
q.push(v);
}
return maxProfit;
}
int main() {
int W = 10;
Item items[] = {{2, 40}, {3, 50}, {4, 65}, {5, 35}};
int n = sizeof(items) / sizeof(items[0]);
for (int i = 0; i < n; i++)
items[i].ratio = (float)items[i].profit / items[i].weight;
cout << "Maximum Profit = " << knapsack(items, n, W) << endl;
return 0;
}

Output:
6.(i).Perform Djikstra’s Algorithm.

Code:
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class DjikstraAlgo
{
public:
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
set<pair<int,int>> st;
vector<int> dist(V, 1e9);
st.insert({0, S});
dist[S] = 0;
while(!st.empty()) {
auto it = *(st.begin());
int node = it.second;
int distance= it.first;
st.erase(it);

for(auto it : adj[node]) {
int adjNode = it[0];
int edge = it[1];

if(distance + edge< dist[adjNode]) {


if(dist[adjNode] != 1e9)
st.erase({dist[adjNode], adjNode});
dist[adjNode] = distance + edge;
st.insert({dist[adjNode], adjNode});
}
} }

return dist;
}
};
int main()
{
int V = 3, E = 3, S = 2;
vector<vector<int>> adj[V];
vector<vector<int>> edges;
vector<int> v1{1, 1}, v2{1, 6}, v3{2,3}, v4{0, 1}, v5{1, 2}, v6{5, 3};
int i = 0;
adj[0].push_back(v1);
adj[0].push_back(v2);
adj[1].push_back(v3);
adj[1].push_back(v4);
adj[2].push_back(v5);
adj[2].push_back(v6);

DjikstraAlgo ans;
vector<int> res = ans.dijkstra(V, adj, S);

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


{
cout << res[i] << " ";
}
cout << endl;
return 0;
}
6.(ii) Perform flyod Warshall Algorithm
Code:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void shortest_path(vector<vector<int>>&matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == -1) {
matrix[i][j] = 1e9;
}
if (i == j) matrix[i][j] = 0;
}}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = min(matrix[i][j],
matrix[i][k] + matrix[k][j]);
}
}}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1e9) {
matrix[i][j] = -1;
}
}}}};
int main() {

int V = 4;
vector<vector<int>> matrix(V, vector<int>(V, -1));
matrix[0][1] = 2;
matrix[1][0] = 1;
matrix[1][2] = 9;
matrix[3][0] = 3;
matrix[3][1] = 7;
matrix[3][2] = 4;
Solution obj;
obj.shortest_path(matrix);
for (auto row : matrix) {
for (auto cell : row) {
cout << cell << " ";
}
cout << endl;
}
return 0;
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy