Aditya8daa Merged

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

DEPARTMENT OF

SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Aditya Kumar UID: 22BCS50108


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:11/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find shortest paths in a graph with
positive edge weights using Dijkstra’s algorithm.

2. Objective: To implement and analyze the efficiency of Dijkstra’s algorithm for finding the
shortest paths in a graph with positive edge weights. The goal is to evaluate the algorithm's
time complexity based on the data structure used for the priority queue (e.g., binary heap
or Fibonacci heap).

3. Algorithm:
Step1:- Initialize:

• Create a distance array dist[] and set all values to infinity (∞) except for the source
node, which is set to 0.
• Use a priority queue (min-heap) to store nodes with their current known shortest
distance.

Step 2:- Push Source:

• Insert the source node into the priority queue with a distance of 0.

Step 3:- While Queue is Not Empty:

• Extract the node u with the minimum distance from the priority queue.
• For each neighboring node v of u, calculate the tentative distance to v through u.
• If this distance is smaller than the current distance in dist[v], update dist[v] and
insert v into the priority queue with the new distance.

Step 4:- Repeat:


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

• Continue this process until the priority queue is empty.

Step 5:- Result:

• At the end, dist[] contains the shortest distance from the source node to all other
nodes.

4. Implementation/Code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

typedef pair<int, int> PII; // Pair to store (distance, vertex)

// Dijkstra's algorithm to find the shortest paths from a source node vector<int> dijkstra(int
source, const vector<vector<PII>>& graph, int V) { priority_queue<PII, vector<PII>,
greater<PII>> pq; // Min-heap priority queue
vector<int> dist(V, INT_MAX); // Initialize distances to infinity

dist[source] = 0; // Distance to the source is 0 pq.push({0, source});


// Push the source into the priority queue while (!pq.empty()) { int u =
pq.top().second; // Get the vertex with the
smallest distance pq.pop();

// Traverse all adjacent vertices of u for (const


auto& neighbor : graph[u]) { int v =
neighbor.second; int weight = neighbor.first;

// Relaxation step if (dist[u] + weight


< dist[v]) { dist[v] = dist[u] + weight;
pq.push({dist[v], v}); // Push updated distance to the priority queue
}
}
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

return dist; // Return the shortest distance to all vertices


}

int main() { int V = 5; // Number of


vertices vector<vector<PII>> graph(V);

// Adding edges (weight, vertex) graph[0].push_back({10,


1}); graph[0].push_back({3, 2}); graph[1].push_back({1,

3}); graph[2].push_back({4, 1}); graph[2].push_back({8, 3});


graph[2].push_back({2, 4}); graph[3].push_back({7, 4});

int source = 0; // Set the source node

// Run Dijkstra's algorithm vector<int> distances = dijkstra(source,


graph, V);
// Output the shortest distances from the source node cout <<
"Shortest distances from node " << source << ":\n"; for (int i = 0; i <
V; ++i) { cout << "Node " << i << " : " << distances[i] << "\n";
}

return 0;
}

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
Using Binary Heap: O((V + E) log V), where V is the number of vertices and E is the
number of edges.
Using Fibonacci Heap: O(E + V log V).

Space Complexity:
The overall space complexity of Dijkstra’s algorithm is O(V + E), where V is the number
of vertices and E is the number of edges.

7. Learning Outcomes:

1. Understanding of Dijkstra's Algorithm: You will learn how to implement and apply
Dijkstra’s algorithm to find the shortest paths in graphs with positive edge weights,
utilizing a priority queue for efficiency.
2. Time and Space Complexity Analysis: You will gain insights into analyzing the time
complexity (O((V + E) log V) using a binary heap) and space complexity (O(V + E)) of
the algorithm.
3. Graph Representation: You will understand how to represent graphs efficiently using
adjacency lists and handle shortest path problems with realworld applications.
Experiment: 9

Student Name: Aditya Kumar UID: 22BCS50103


Branch: BE CSE Section: 22BCS630/B
Semester: 5th Date of Performance:25/10/24
Subject Name: AP _LAB 01 Subject Code: 22CSP-314

1.Aim:
Backtracking/Dynamic Programming: To demonstrate the concept of Backtracking and d ynamic
Programming.

2.Objective:
Your goal is to ind the number of ways to construct an array such that consecutive positions
containdifferent values.
Speci ically, we want to construct an array with elements such that each element between and ,
inclusive. We also want the irst and last elements of the arrayto be and .
Given , and , ind the number of ways to construct such an array. Since the answer may be large, only
ind it modulo .

3.Implementation/Code:
#include <iostream>
#include <vector>

using namespace std;

const long MOD = 1e9 + 7;

long countArray(int n, int k, int x) { //


Create two arrays for DP: f[i] and g[i]
vector<long> f(n + 1, 0); vector<long>
g(n + 1, 0);
// Base cases
f[2] = 1; g[2]
= 0;

// Fill DP arrays for (int i = 3; i <= n;


i++) { f[i] = (g[i - 1] + (k - 2) * f[i - 1])
% MOD; g[i] = ((k - 1) * f[i - 1]) %
MOD;
}

// Return the result based on x return


(x == 1) ? g[n] : f[n];
}

int main() { int n,


k, x; cin >> n >> k
>> x;

cout << countArray(n, k, x) << endl;

return 0;
}
4. Output:

Problem -2

1. Aim:
Given a chess board having N×N cells, you need to place N queens on the board in such a way that no
queen attacks any other queen.

2. Objective:
The objective is to solve the N-Queens problem, which involves placing N queens on an N×N
chessboard such that no two queens threaten each other. This means that no two queens can be placed in
the same row, column, or diagonal. The challenge is to ind all possible con igurations for placing the
queens on the board.

3. Code:
#include <iostream>

#include <vector> using

namespace std; class

NQueens { public:

NQueens(int n) : N(n) {

board.resize(N, vector<int>(N, 0));

}
void solve() {

placeQueens(0);

private:

int N;

vector<vector<int>> board;

void printBoard() {

for (const auto& row : board) {

for (int cell : row) { cout

<< (cell ? "Q " : ". ");

cout << endl;

cout << endl;

bool isSafe(int row, int col) { // Check this

column on upper side for (int i = 0; i < row;

i++) if (board[i][col]) return false; //

Check upper diagonal on left side for (int i =

row, j = col; i >= 0 && j >= 0; i--, j--) if

(board[i][j]) return false;


// Check upper diagonal on right side for

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

if (board[i][j]) return false; return true; } void

placeQueens(int row) {

if (row == N) {
printBoard();

return;

for (int col = 0; col < N; col++) { if (isSafe(row, col)) {

board[row][col] = 1; // Place queen placeQueens(row +

1); // Recur to place the next queen board[row][col] = 0;

// Backtrack

} } }};

int main() {

int N;

cout << "Enter the number of queens: ";

cin >> N;

NQueens queens(N);

queens.solve(); return

0;

}
4. Output:

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative values between
adjacent elements.

ii. Understand how to implement a two-pass algorithm to achieve the optimal solution in such
scenarios. iii. learn how to apply cumulative cost calculations in scenarios involving
variable constraints.
iv. They will understand how to optimize and calculate required values based on a progressive
increase in factors, such as the distance Marc must walk per cupcake.

v. This exercise will enhance problem-solving skills in handling scenarios with incremental
constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Aditya Kumar UID: 22BCS50103


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:18/10/24
Subject Name: AP _LAB Subject Code: 22CSP-314

1. Aim:
Problem Statement: - Alice is a kindergarten teacher. She wants to give some candies
to the children in her class. All the children sit in a line and each of them has a rating
score according to his or her performance in the class. Alice wants to give at least 1
candy to each child. If two children sit next to each other, then the one with the higher
rating must get more candies. Alice wants to minimize the total number of candies
she must buy.
2. Objective:
The objective is to determine the minimum number of candies Alice needs to
distribute to children seated in a line based on their rating scores. Each child must
receive at least one candy, and children with higher ratings than their adjacent
neighbors must receive more candies than those neighbors.

3. Implementation/Code:
public class Solution { static BigInteger candies(int n, int[] arr)
{ int[] cache = new int[arr.length];
cache[0] = 1; for (int i = 1; i <
arr.length; i++) { if (arr[i-1] <
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

arr[i]) { cache[i] = cache[i-1]


+ 1;
}

if (arr[i-1] >= arr[i]) {


cache[i] = 1;
}
}
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > arr[i+1]) { if (cache[i] <=
cache[i+1]) { cache[i] = cache[i+1]
+ 1;
}
}
}

BigInteger sum = BigInteger.valueOf(0); for (int i =


0; i < cache.length; i++) { sum = sum.add(BigInteger.valueOf(cache[i]));
}

return sum;
}

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Problem -2
1. Aim:
Problem Statement: - Marc loves cupcakes, but he also likes to stay fit. Each cupcake
has a calorie count, and Marc can walk a distance to expend those calories. If Marc has
eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least 2j
*cmiles to maintain his weight.

2. Objective:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

The objective is to calculate the minimum total distance Marc needs to walk to offset
the calories from the cupcakes he has eaten. Given that Marc must walk an increasing
distance proportional to the number of cupcakes consumed, the goal is to determine the
total walking distance required to balance out the calorie intake from all cupcakes.

3. Code:
class Result { public static long
marcsCakewalk(List<Integer> calorie) {
// Write your code here
Collections.sort(calorie, Collections.reverseOrder());
long totalCandies = 0; for (int i = 0; i < calorie.size();
i++) { totalCandies += (1L << i) * calorie.get(i);
}

return totalCandies;
} }

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative
values between adjacent elements.
ii. Understand how to implement a two-pass algorithm to achieve the optimal
solution in such scenarios.

iii. learn how to apply cumulative cost calculations in scenarios involving variable
constraints.
iv. They will understand how to optimize and calculate required values based on a
progressive increase in factors, such as the distance Marc must walk per cupcake.
v. This exercise will enhance problem-solving skills in handling scenarios with
incremental constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 9

Student Name: Aditya Kumar UID: 22BCS50103


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:17/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.

2. Objective: To develop a program to find all occurrences of a pattern P in a


string S, and analyze the time complexity based on different algorithms (e.g., brute force,
KMP, or Boyer-Moore). Compare performance for varying pattern lengths and input sizes.

3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)

• Initialize an array lps[] of size m (length of P).


• Set lps[0] = 0 and iterate through P to fill the rest of the lps[] values, where lps[i]
represents the longest proper prefix which is also a suffix for the substring P[0…i].
• Time complexity: O(m).

Step 2: Start Matching P in S

• Set two pointers, i = 0 for S and j = 0 for P.


• Traverse through the string S. If P[j] == S[i], increment both i and j.
• If there is a mismatch, use lps[] to update j (i.e., set j = lps[j-1]), without resetting i.

Step 3: Record Occurrence

• If j reaches the length of P (i.e., j == m), a full pattern match is found. Record the
index i - j as the occurrence.
• Then, reset j = lps[j-1] to continue searching.

Step 4: End the Search

• Continue until i traverses the entire string S.


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

4. Implementation/Code:

#include <iostream> #include


<vector> using namespace
std;
// Function to build the LPS (Longest Prefix Suffix) array vector<int>
buildLPS(const string& P) { int m = P.length(); vector<int>
lps(m, 0);
int len = 0; // length of previous longest prefix suffix int i
= 1;

while (i < m) { if (P[i] == P[len]) { len++;


lps[i] = len; i++; } else
{ if (len != 0) { len = lps[len - 1];
// use previous lps
} else { lps[i]
= 0; i++;
}
} }
return lps;
}

// KMP search function to find all occurrences of P in S


void KMPsearch(const string& S, const string& P) {
int n = S.length(); int m = P.length(); vector<int>
lps = buildLPS(P);

int i = 0; // index for S int j


= 0; // index for P

bool found = false; // flag to check if any pattern is found

cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"\n"; cout
<< "--------------------------------------------\n";
while (i < n) { if (P[j] == S[i]) {
i++; j++;
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

if (j == m)

{ found = true; cout << ">> Pattern found at index: " <<
(i - j) << " <<\n"; j = lps[j - 1]; // get the index from LPS array

} else if (i < n && P[j] != S[i]) { if (j


!= 0) { j = lps[j - 1]; // use the LPS
array
} else { i++;
}
}
}

if (!found) { cout << ">> No occurrences of the pattern


found. <<\n";
}

cout << "--------------------------------------------\n";


}

int main() {
string S = "ababcababcababc";
string P = "ababc"; KMPsearch(S, P); return
0;

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
The overall time complexity is: O(n + m) Space Complexity: The overall space
complexity is: O(m).

7. Learning Outcomes:

• Efficient String Matching:


You will understand how the KMP algorithm efficiently finds all occurrences of a
pattern P in a string S, avoiding redundant comparisons.
• LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix Suffix (LPS) array to
skip unnecessary comparisons, optimizing the search process.
• Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and space complexity,
understanding why KMP achieves linear time complexity O(n + m) with only O(m)
space overhead.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Ankur Gangwar UID: 22BCS50119


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:11/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find shortest paths in a graph with
positive edge weights using Dijkstra’s algorithm.

2. Objective: To implement and analyze the efficiency of Dijkstra’s algorithm for finding the
shortest paths in a graph with positive edge weights. The goal is to evaluate the algorithm's
time complexity based on the data structure used for the priority queue (e.g., binary heap
or Fibonacci heap).

3. Algorithm:
Step1:- Initialize:

• Create a distance array dist[] and set all values to infinity (∞) except for the source
node, which is set to 0.
• Use a priority queue (min-heap) to store nodes with their current known shortest
distance.

Step 2:- Push Source:

• Insert the source node into the priority queue with a distance of 0.

Step 3:- While Queue is Not Empty:

• Extract the node u with the minimum distance from the priority queue.
• For each neighboring node v of u, calculate the tentative distance to v through u.
• If this distance is smaller than the current distance in dist[v], update dist[v] and
insert v into the priority queue with the new distance.

Step 4:- Repeat:


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

• Continue this process until the priority queue is empty.

Step 5:- Result:

• At the end, dist[] contains the shortest distance from the source node to all other
nodes.

4. Implementation/Code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

typedef pair<int, int> PII; // Pair to store (distance, vertex)

// Dijkstra's algorithm to find the shortest paths from a source node vector<int> dijkstra(int
source, const vector<vector<PII>>& graph, int V) { priority_queue<PII, vector<PII>,
greater<PII>> pq; // Min-heap priority queue
vector<int> dist(V, INT_MAX); // Initialize distances to infinity

dist[source] = 0; // Distance to the source is 0 pq.push({0, source});


// Push the source into the priority queue while (!pq.empty()) { int u =
pq.top().second; // Get the vertex with the
smallest distance pq.pop();

// Traverse all adjacent vertices of u for (const


auto& neighbor : graph[u]) { int v =
neighbor.second; int weight = neighbor.first;

// Relaxation step if (dist[u] + weight


< dist[v]) { dist[v] = dist[u] + weight;
pq.push({dist[v], v}); // Push updated distance to the priority queue
}
}
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

return dist; // Return the shortest distance to all vertices


}

int main() { int V = 5; // Number of


vertices vector<vector<PII>> graph(V);

// Adding edges (weight, vertex) graph[0].push_back({10,


1}); graph[0].push_back({3, 2}); graph[1].push_back({1,

3}); graph[2].push_back({4, 1}); graph[2].push_back({8, 3});


graph[2].push_back({2, 4}); graph[3].push_back({7, 4});

int source = 0; // Set the source node

// Run Dijkstra's algorithm vector<int> distances = dijkstra(source,


graph, V);
// Output the shortest distances from the source node cout <<
"Shortest distances from node " << source << ":\n"; for (int i = 0; i <
V; ++i) { cout << "Node " << i << " : " << distances[i] << "\n";
}

return 0;
}

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
Using Binary Heap: O((V + E) log V), where V is the number of vertices and E is the
number of edges.
Using Fibonacci Heap: O(E + V log V).

Space Complexity:
The overall space complexity of Dijkstra’s algorithm is O(V + E), where V is the number
of vertices and E is the number of edges.

7. Learning Outcomes:

1. Understanding of Dijkstra's Algorithm: You will learn how to implement and apply
Dijkstra’s algorithm to find the shortest paths in graphs with positive edge weights,
utilizing a priority queue for efficiency.
2. Time and Space Complexity Analysis: You will gain insights into analyzing the time
complexity (O((V + E) log V) using a binary heap) and space complexity (O(V + E)) of
the algorithm.
3. Graph Representation: You will understand how to represent graphs efficiently using
adjacency lists and handle shortest path problems with realworld applications.
Experiment: 9

Student Name: Ankur Gangwar UID: 22BCS50119


Branch: BE CSE Section: 22BCS630/B
Semester: 5th Date of Performance:25/10/24
Subject Name: AP _LAB 01 Subject Code: 22CSP-314

1.Aim:
Backtracking/Dynamic Programming: To demonstrate the concept of Backtracking and d ynamic
Programming.

2.Objective:
Your goal is to ind the number of ways to construct an array such that consecutive positions
containdifferent values.
Speci ically, we want to construct an array with elements such that each element between and ,
inclusive. We also want the irst and last elements of the arrayto be and .
Given , and , ind the number of ways to construct such an array. Since the answer may be large, only
ind it modulo .

3.Implementation/Code:
#include <iostream>
#include <vector>

using namespace std;

const long MOD = 1e9 + 7;

long countArray(int n, int k, int x) { //


Create two arrays for DP: f[i] and g[i]
vector<long> f(n + 1, 0); vector<long>
g(n + 1, 0);
// Base cases
f[2] = 1; g[2]
= 0;

// Fill DP arrays for (int i = 3; i <= n;


i++) { f[i] = (g[i - 1] + (k - 2) * f[i - 1])
% MOD; g[i] = ((k - 1) * f[i - 1]) %
MOD;
}

// Return the result based on x return


(x == 1) ? g[n] : f[n];
}

int main() { int n,


k, x; cin >> n >> k
>> x;

cout << countArray(n, k, x) << endl;

return 0;
}
4. Output:

Problem -2

1. Aim:
Given a chess board having N×N cells, you need to place N queens on the board in such a way that no
queen attacks any other queen.

2. Objective:
The objective is to solve the N-Queens problem, which involves placing N queens on an N×N
chessboard such that no two queens threaten each other. This means that no two queens can be placed in
the same row, column, or diagonal. The challenge is to ind all possible con igurations for placing the
queens on the board.

3. Code:
#include <iostream>

#include <vector> using

namespace std; class

NQueens { public:

NQueens(int n) : N(n) {

board.resize(N, vector<int>(N, 0));

}
void solve() {

placeQueens(0);

private:

int N;

vector<vector<int>> board;

void printBoard() {

for (const auto& row : board) {

for (int cell : row) { cout

<< (cell ? "Q " : ". ");

cout << endl;

cout << endl;

bool isSafe(int row, int col) { // Check this

column on upper side for (int i = 0; i < row;

i++) if (board[i][col]) return false; //

Check upper diagonal on left side for (int i =

row, j = col; i >= 0 && j >= 0; i--, j--) if

(board[i][j]) return false;


// Check upper diagonal on right side for

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

if (board[i][j]) return false; return true; } void

placeQueens(int row) {

if (row == N) {
printBoard();

return;

for (int col = 0; col < N; col++) { if (isSafe(row, col)) {

board[row][col] = 1; // Place queen placeQueens(row +

1); // Recur to place the next queen board[row][col] = 0;

// Backtrack

} } }};

int main() {

int N;

cout << "Enter the number of queens: ";

cin >> N;

NQueens queens(N);

queens.solve(); return

0;

}
4. Output:

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative values between
adjacent elements.

ii. Understand how to implement a two-pass algorithm to achieve the optimal solution in such
scenarios. iii. learn how to apply cumulative cost calculations in scenarios involving
variable constraints.
iv. They will understand how to optimize and calculate required values based on a progressive
increase in factors, such as the distance Marc must walk per cupcake.

v. This exercise will enhance problem-solving skills in handling scenarios with incremental
constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 9

Student Name: Ankur Gangwar UID: 22BCS50119


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:17/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.

2. Objective: To develop a program to find all occurrences of a pattern P in a


string S, and analyze the time complexity based on different algorithms (e.g., brute force,
KMP, or Boyer-Moore). Compare performance for varying pattern lengths and input sizes.

3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)

• Initialize an array lps[] of size m (length of P).


• Set lps[0] = 0 and iterate through P to fill the rest of the lps[] values, where lps[i]
represents the longest proper prefix which is also a suffix for the substring P[0…i].
• Time complexity: O(m).

Step 2: Start Matching P in S

• Set two pointers, i = 0 for S and j = 0 for P.


• Traverse through the string S. If P[j] == S[i], increment both i and j.
• If there is a mismatch, use lps[] to update j (i.e., set j = lps[j-1]), without resetting i.

Step 3: Record Occurrence

• If j reaches the length of P (i.e., j == m), a full pattern match is found. Record the
index i - j as the occurrence.
• Then, reset j = lps[j-1] to continue searching.

Step 4: End the Search

• Continue until i traverses the entire string S.


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

4. Implementation/Code:

#include <iostream> #include


<vector> using namespace
std;
// Function to build the LPS (Longest Prefix Suffix) array vector<int>
buildLPS(const string& P) { int m = P.length(); vector<int>
lps(m, 0);
int len = 0; // length of previous longest prefix suffix int i
= 1;

while (i < m) { if (P[i] == P[len]) { len++;


lps[i] = len; i++; } else
{ if (len != 0) { len = lps[len - 1];
// use previous lps
} else { lps[i]
= 0; i++;
}
} }
return lps;
}

// KMP search function to find all occurrences of P in S


void KMPsearch(const string& S, const string& P) {
int n = S.length(); int m = P.length(); vector<int>
lps = buildLPS(P);

int i = 0; // index for S int j


= 0; // index for P

bool found = false; // flag to check if any pattern is found

cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"\n"; cout
<< "--------------------------------------------\n";
while (i < n) { if (P[j] == S[i]) {
i++; j++;
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

if (j == m)

{ found = true; cout << ">> Pattern found at index: " <<
(i - j) << " <<\n"; j = lps[j - 1]; // get the index from LPS array

} else if (i < n && P[j] != S[i]) { if (j


!= 0) { j = lps[j - 1]; // use the LPS
array
} else { i++;
}
}
}

if (!found) { cout << ">> No occurrences of the pattern


found. <<\n";
}

cout << "--------------------------------------------\n";


}

int main() {
string S = "ababcababcababc";
string P = "ababc"; KMPsearch(S, P); return
0;

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
The overall time complexity is: O(n + m) Space Complexity: The overall space
complexity is: O(m).

7. Learning Outcomes:

• Efficient String Matching:


You will understand how the KMP algorithm efficiently finds all occurrences of a
pattern P in a string S, avoiding redundant comparisons.
• LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix Suffix (LPS) array to
skip unnecessary comparisons, optimizing the search process.
• Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and space complexity,
understanding why KMP achieves linear time complexity O(n + m) with only O(m)
space overhead.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Ankur Gangwar UID: 22BCS50119


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:18/10/24
Subject Name: AP _LAB Subject Code: 22CSP-314

1. Aim:
Problem Statement: - Alice is a kindergarten teacher. She wants to give some candies
to the children in her class. All the children sit in a line and each of them has a rating
score according to his or her performance in the class. Alice wants to give at least 1
candy to each child. If two children sit next to each other, then the one with the higher
rating must get more candies. Alice wants to minimize the total number of candies
she must buy.
2. Objective:
The objective is to determine the minimum number of candies Alice needs to
distribute to children seated in a line based on their rating scores. Each child must
receive at least one candy, and children with higher ratings than their adjacent
neighbors must receive more candies than those neighbors.

3. Implementation/Code:
public class Solution { static BigInteger candies(int n, int[] arr)
{ int[] cache = new int[arr.length];
cache[0] = 1; for (int i = 1; i <
arr.length; i++) { if (arr[i-1] <
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

arr[i]) { cache[i] = cache[i-1]


+ 1;
}

if (arr[i-1] >= arr[i]) {


cache[i] = 1;
}
}
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > arr[i+1]) { if (cache[i] <=
cache[i+1]) { cache[i] = cache[i+1]
+ 1;
}
}
}

BigInteger sum = BigInteger.valueOf(0); for (int i =


0; i < cache.length; i++) { sum = sum.add(BigInteger.valueOf(cache[i]));
}

return sum;
}

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Problem -2
1. Aim:
Problem Statement: - Marc loves cupcakes, but he also likes to stay fit. Each cupcake
has a calorie count, and Marc can walk a distance to expend those calories. If Marc has
eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least 2j
*cmiles to maintain his weight.

2. Objective:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

The objective is to calculate the minimum total distance Marc needs to walk to offset
the calories from the cupcakes he has eaten. Given that Marc must walk an increasing
distance proportional to the number of cupcakes consumed, the goal is to determine the
total walking distance required to balance out the calorie intake from all cupcakes.

3. Code:
class Result { public static long
marcsCakewalk(List<Integer> calorie) {
// Write your code here
Collections.sort(calorie, Collections.reverseOrder());
long totalCandies = 0; for (int i = 0; i < calorie.size();
i++) { totalCandies += (1L << i) * calorie.get(i);
}

return totalCandies;
} }

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative
values between adjacent elements.
ii. Understand how to implement a two-pass algorithm to achieve the optimal
solution in such scenarios.

iii. learn how to apply cumulative cost calculations in scenarios involving variable
constraints.
iv. They will understand how to optimize and calculate required values based on a
progressive increase in factors, such as the distance Marc must walk per cupcake.
v. This exercise will enhance problem-solving skills in handling scenarios with
incremental constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Sudhir UID: 22BCS50108


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:18/10/24
Subject Name: AP _LAB Subject Code: 22CSP-314

1. Aim:
Problem Statement: - Alice is a kindergarten teacher. She wants to give some candies
to the children in her class. All the children sit in a line and each of them has a rating
score according to his or her performance in the class. Alice wants to give at least 1
candy to each child. If two children sit next to each other, then the one with the higher
rating must get more candies. Alice wants to minimize the total number of candies
she must buy.
2. Objective:
The objective is to determine the minimum number of candies Alice needs to
distribute to children seated in a line based on their rating scores. Each child must
receive at least one candy, and children with higher ratings than their adjacent
neighbors must receive more candies than those neighbors.

3. Implementation/Code:
public class Solution { static BigInteger candies(int n, int[] arr)
{ int[] cache = new int[arr.length];
cache[0] = 1; for (int i = 1; i <
arr.length; i++) { if (arr[i-1] <
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

arr[i]) { cache[i] = cache[i-1]


+ 1;
}

if (arr[i-1] >= arr[i]) {


cache[i] = 1;
}
}
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > arr[i+1]) { if (cache[i] <=
cache[i+1]) { cache[i] = cache[i+1]
+ 1;
}
}
}

BigInteger sum = BigInteger.valueOf(0); for (int i =


0; i < cache.length; i++) { sum = sum.add(BigInteger.valueOf(cache[i]));
}

return sum;
}

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Problem -2
1. Aim:
Problem Statement: - Marc loves cupcakes, but he also likes to stay fit. Each cupcake
has a calorie count, and Marc can walk a distance to expend those calories. If Marc has
eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least 2j
*cmiles to maintain his weight.

2. Objective:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

The objective is to calculate the minimum total distance Marc needs to walk to offset
the calories from the cupcakes he has eaten. Given that Marc must walk an increasing
distance proportional to the number of cupcakes consumed, the goal is to determine the
total walking distance required to balance out the calorie intake from all cupcakes.

3. Code:
class Result { public static long
marcsCakewalk(List<Integer> calorie) {
// Write your code here
Collections.sort(calorie, Collections.reverseOrder());
long totalCandies = 0; for (int i = 0; i < calorie.size();
i++) { totalCandies += (1L << i) * calorie.get(i);
}

return totalCandies;
} }

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative
values between adjacent elements.
ii. Understand how to implement a two-pass algorithm to achieve the optimal
solution in such scenarios.

iii. learn how to apply cumulative cost calculations in scenarios involving variable
constraints.
iv. They will understand how to optimize and calculate required values based on a
progressive increase in factors, such as the distance Marc must walk per cupcake.
v. This exercise will enhance problem-solving skills in handling scenarios with
incremental constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER
Experiment: 9

Student Name: Sudhir UID: 22BCS50108


Branch: BE CSE Section: 22BCS630/B
Semester: 5th Date of Performance:25/10/24
Subject Name: AP _LAB 01 Subject Code: 22CSP-314

1.Aim:
Backtracking/Dynamic Programming: To demonstrate the concept of Backtracking and d ynamic
Programming.

2.Objective:
Your goal is to ind the number of ways to construct an array such that consecutive positions
containdifferent values.
Speci ically, we want to construct an array with elements such that each element between and ,
inclusive. We also want the irst and last elements of the arrayto be and .
Given , and , ind the number of ways to construct such an array. Since the answer may be large, only
ind it modulo .

3.Implementation/Code:
#include <iostream>
#include <vector>

using namespace std;

const long MOD = 1e9 + 7;

long countArray(int n, int k, int x) { //


Create two arrays for DP: f[i] and g[i]
vector<long> f(n + 1, 0); vector<long>
g(n + 1, 0);
// Base cases
f[2] = 1; g[2]
= 0;

// Fill DP arrays for (int i = 3; i <= n;


i++) { f[i] = (g[i - 1] + (k - 2) * f[i - 1])
% MOD; g[i] = ((k - 1) * f[i - 1]) %
MOD;
}

// Return the result based on x return


(x == 1) ? g[n] : f[n];
}

int main() { int n,


k, x; cin >> n >> k
>> x;

cout << countArray(n, k, x) << endl;

return 0;
}
4. Output:

Problem -2

1. Aim:
Given a chess board having N×N cells, you need to place N queens on the board in such a way that no
queen attacks any other queen.

2. Objective:
The objective is to solve the N-Queens problem, which involves placing N queens on an N×N
chessboard such that no two queens threaten each other. This means that no two queens can be placed in
the same row, column, or diagonal. The challenge is to ind all possible con igurations for placing the
queens on the board.

3. Code:
#include <iostream>

#include <vector> using

namespace std; class

NQueens { public:

NQueens(int n) : N(n) {

board.resize(N, vector<int>(N, 0));

}
void solve() {

placeQueens(0);

private:

int N;

vector<vector<int>> board;

void printBoard() {

for (const auto& row : board) {

for (int cell : row) { cout

<< (cell ? "Q " : ". ");

cout << endl;

cout << endl;

bool isSafe(int row, int col) { // Check this

column on upper side for (int i = 0; i < row;

i++) if (board[i][col]) return false; //

Check upper diagonal on left side for (int i =

row, j = col; i >= 0 && j >= 0; i--, j--) if

(board[i][j]) return false;


// Check upper diagonal on right side for

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

if (board[i][j]) return false; return true; } void

placeQueens(int row) {

if (row == N) {
printBoard();

return;

for (int col = 0; col < N; col++) { if (isSafe(row, col)) {

board[row][col] = 1; // Place queen placeQueens(row +

1); // Recur to place the next queen board[row][col] = 0;

// Backtrack

} } }};

int main() {

int N;

cout << "Enter the number of queens: ";

cin >> N;

NQueens queens(N);

queens.solve(); return

0;

}
4. Output:

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative values between
adjacent elements.

ii. Understand how to implement a two-pass algorithm to achieve the optimal solution in such
scenarios. iii. learn how to apply cumulative cost calculations in scenarios involving
variable constraints.
iv. They will understand how to optimize and calculate required values based on a progressive
increase in factors, such as the distance Marc must walk per cupcake.

v. This exercise will enhance problem-solving skills in handling scenarios with incremental
constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Sudhir UID: 22BCS50108


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:11/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find shortest paths in a graph with
positive edge weights using Dijkstra’s algorithm.

2. Objective: To implement and analyze the efficiency of Dijkstra’s algorithm for finding the
shortest paths in a graph with positive edge weights. The goal is to evaluate the algorithm's
time complexity based on the data structure used for the priority queue (e.g., binary heap
or Fibonacci heap).

3. Algorithm:
Step1:- Initialize:

• Create a distance array dist[] and set all values to infinity (∞) except for the source
node, which is set to 0.
• Use a priority queue (min-heap) to store nodes with their current known shortest
distance.

Step 2:- Push Source:

• Insert the source node into the priority queue with a distance of 0.

Step 3:- While Queue is Not Empty:

• Extract the node u with the minimum distance from the priority queue.
• For each neighboring node v of u, calculate the tentative distance to v through u.
• If this distance is smaller than the current distance in dist[v], update dist[v] and
insert v into the priority queue with the new distance.

Step 4:- Repeat:


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

• Continue this process until the priority queue is empty.

Step 5:- Result:

• At the end, dist[] contains the shortest distance from the source node to all other
nodes.

4. Implementation/Code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

typedef pair<int, int> PII; // Pair to store (distance, vertex)

// Dijkstra's algorithm to find the shortest paths from a source node vector<int> dijkstra(int
source, const vector<vector<PII>>& graph, int V) { priority_queue<PII, vector<PII>,
greater<PII>> pq; // Min-heap priority queue
vector<int> dist(V, INT_MAX); // Initialize distances to infinity

dist[source] = 0; // Distance to the source is 0 pq.push({0, source});


// Push the source into the priority queue while (!pq.empty()) { int u =
pq.top().second; // Get the vertex with the
smallest distance pq.pop();

// Traverse all adjacent vertices of u for (const


auto& neighbor : graph[u]) { int v =
neighbor.second; int weight = neighbor.first;

// Relaxation step if (dist[u] + weight


< dist[v]) { dist[v] = dist[u] + weight;
pq.push({dist[v], v}); // Push updated distance to the priority queue
}
}
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

return dist; // Return the shortest distance to all vertices


}

int main() { int V = 5; // Number of


vertices vector<vector<PII>> graph(V);

// Adding edges (weight, vertex) graph[0].push_back({10,


1}); graph[0].push_back({3, 2}); graph[1].push_back({1,

3}); graph[2].push_back({4, 1}); graph[2].push_back({8, 3});


graph[2].push_back({2, 4}); graph[3].push_back({7, 4});

int source = 0; // Set the source node

// Run Dijkstra's algorithm vector<int> distances = dijkstra(source,


graph, V);
// Output the shortest distances from the source node cout <<
"Shortest distances from node " << source << ":\n"; for (int i = 0; i <
V; ++i) { cout << "Node " << i << " : " << distances[i] << "\n";
}

return 0;
}

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
Using Binary Heap: O((V + E) log V), where V is the number of vertices and E is the
number of edges.
Using Fibonacci Heap: O(E + V log V).

Space Complexity:
The overall space complexity of Dijkstra’s algorithm is O(V + E), where V is the number
of vertices and E is the number of edges.

7. Learning Outcomes:

1. Understanding of Dijkstra's Algorithm: You will learn how to implement and apply
Dijkstra’s algorithm to find the shortest paths in graphs with positive edge weights,
utilizing a priority queue for efficiency.
2. Time and Space Complexity Analysis: You will gain insights into analyzing the time
complexity (O((V + E) log V) using a binary heap) and space complexity (O(V + E)) of
the algorithm.
3. Graph Representation: You will understand how to represent graphs efficiently using
adjacency lists and handle shortest path problems with realworld applications.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 9

Student Name: Sudhir UID: 22BCS50108


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:17/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.

2. Objective: To develop a program to find all occurrences of a pattern P in a


string S, and analyze the time complexity based on different algorithms (e.g., brute force,
KMP, or Boyer-Moore). Compare performance for varying pattern lengths and input sizes.

3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)

• Initialize an array lps[] of size m (length of P).


• Set lps[0] = 0 and iterate through P to fill the rest of the lps[] values, where lps[i]
represents the longest proper prefix which is also a suffix for the substring P[0…i].
• Time complexity: O(m).

Step 2: Start Matching P in S

• Set two pointers, i = 0 for S and j = 0 for P.


• Traverse through the string S. If P[j] == S[i], increment both i and j.
• If there is a mismatch, use lps[] to update j (i.e., set j = lps[j-1]), without resetting i.

Step 3: Record Occurrence

• If j reaches the length of P (i.e., j == m), a full pattern match is found. Record the
index i - j as the occurrence.
• Then, reset j = lps[j-1] to continue searching.

Step 4: End the Search

• Continue until i traverses the entire string S.


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

4. Implementation/Code:

#include <iostream> #include


<vector> using namespace
std;
// Function to build the LPS (Longest Prefix Suffix) array vector<int>
buildLPS(const string& P) { int m = P.length(); vector<int>
lps(m, 0);
int len = 0; // length of previous longest prefix suffix int i
= 1;

while (i < m) { if (P[i] == P[len]) { len++;


lps[i] = len; i++; } else
{ if (len != 0) { len = lps[len - 1];
// use previous lps
} else { lps[i]
= 0; i++;
}
} }
return lps;
}

// KMP search function to find all occurrences of P in S


void KMPsearch(const string& S, const string& P) {
int n = S.length(); int m = P.length(); vector<int>
lps = buildLPS(P);

int i = 0; // index for S int j


= 0; // index for P

bool found = false; // flag to check if any pattern is found

cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"\n"; cout
<< "--------------------------------------------\n";
while (i < n) { if (P[j] == S[i]) {
i++; j++;
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

if (j == m)

{ found = true; cout << ">> Pattern found at index: " <<
(i - j) << " <<\n"; j = lps[j - 1]; // get the index from LPS array

} else if (i < n && P[j] != S[i]) { if (j


!= 0) { j = lps[j - 1]; // use the LPS
array
} else { i++;
}
}
}

if (!found) { cout << ">> No occurrences of the pattern


found. <<\n";
}

cout << "--------------------------------------------\n";


}

int main() {
string S = "ababcababcababc";
string P = "ababc"; KMPsearch(S, P); return
0;

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
The overall time complexity is: O(n + m) Space Complexity: The overall space
complexity is: O(m).

7. Learning Outcomes:

• Efficient String Matching:


You will understand how the KMP algorithm efficiently finds all occurrences of a
pattern P in a string S, avoiding redundant comparisons.
• LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix Suffix (LPS) array to
skip unnecessary comparisons, optimizing the search process.
• Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and space complexity,
understanding why KMP achieves linear time complexity O(n + m) with only O(m)
space overhead.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Vikrant Chib UID: 22BCS50099


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:18/10/24
Subject Name: AP _LAB Subject Code: 22CSP-314

1. Aim:
Problem Statement: - Alice is a kindergarten teacher. She wants to give some candies
to the children in her class. All the children sit in a line and each of them has a rating
score according to his or her performance in the class. Alice wants to give at least 1
candy to each child. If two children sit next to each other, then the one with the higher
rating must get more candies. Alice wants to minimize the total number of candies
she must buy.
2. Objective:
The objective is to determine the minimum number of candies Alice needs to
distribute to children seated in a line based on their rating scores. Each child must
receive at least one candy, and children with higher ratings than their adjacent
neighbors must receive more candies than those neighbors.

3. Implementation/Code:
public class Solution { static BigInteger candies(int n, int[] arr)
{ int[] cache = new int[arr.length];
cache[0] = 1; for (int i = 1; i <
arr.length; i++) { if (arr[i-1] <
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

arr[i]) { cache[i] = cache[i-1]


+ 1;
}

if (arr[i-1] >= arr[i]) {


cache[i] = 1;
}
}
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > arr[i+1]) { if (cache[i] <=
cache[i+1]) { cache[i] = cache[i+1]
+ 1;
}
}
}

BigInteger sum = BigInteger.valueOf(0); for (int i =


0; i < cache.length; i++) { sum = sum.add(BigInteger.valueOf(cache[i]));
}

return sum;
}

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Problem -2
1. Aim:
Problem Statement: - Marc loves cupcakes, but he also likes to stay fit. Each cupcake
has a calorie count, and Marc can walk a distance to expend those calories. If Marc has
eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least 2j
*cmiles to maintain his weight.

2. Objective:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

The objective is to calculate the minimum total distance Marc needs to walk to offset
the calories from the cupcakes he has eaten. Given that Marc must walk an increasing
distance proportional to the number of cupcakes consumed, the goal is to determine the
total walking distance required to balance out the calorie intake from all cupcakes.

3. Code:
class Result { public static long
marcsCakewalk(List<Integer> calorie) {
// Write your code here
Collections.sort(calorie, Collections.reverseOrder());
long totalCandies = 0; for (int i = 0; i < calorie.size();
i++) { totalCandies += (1L << i) * calorie.get(i);
}

return totalCandies;
} }

4. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative
values between adjacent elements.
ii. Understand how to implement a two-pass algorithm to achieve the optimal
solution in such scenarios.

iii. learn how to apply cumulative cost calculations in scenarios involving variable
constraints.
iv. They will understand how to optimize and calculate required values based on a
progressive increase in factors, such as the distance Marc must walk per cupcake.
v. This exercise will enhance problem-solving skills in handling scenarios with
incremental constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 9

Student Name: Vikrant Chib UID: 22BCS50099


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:17/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.

2. Objective: To develop a program to find all occurrences of a pattern P in a


string S, and analyze the time complexity based on different algorithms (e.g., brute force,
KMP, or Boyer-Moore). Compare performance for varying pattern lengths and input sizes.

3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)

• Initialize an array lps[] of size m (length of P).


• Set lps[0] = 0 and iterate through P to fill the rest of the lps[] values, where lps[i]
represents the longest proper prefix which is also a suffix for the substring P[0…i].
• Time complexity: O(m).

Step 2: Start Matching P in S

• Set two pointers, i = 0 for S and j = 0 for P.


• Traverse through the string S. If P[j] == S[i], increment both i and j.
• If there is a mismatch, use lps[] to update j (i.e., set j = lps[j-1]), without resetting i.

Step 3: Record Occurrence

• If j reaches the length of P (i.e., j == m), a full pattern match is found. Record the
index i - j as the occurrence.
• Then, reset j = lps[j-1] to continue searching.

Step 4: End the Search

• Continue until i traverses the entire string S.


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

4. Implementation/Code:

#include <iostream> #include


<vector> using namespace
std;
// Function to build the LPS (Longest Prefix Suffix) array vector<int>
buildLPS(const string& P) { int m = P.length(); vector<int>
lps(m, 0);
int len = 0; // length of previous longest prefix suffix int i
= 1;

while (i < m) { if (P[i] == P[len]) { len++;


lps[i] = len; i++; } else
{ if (len != 0) { len = lps[len - 1];
// use previous lps
} else { lps[i]
= 0; i++;
}
} }
return lps;
}

// KMP search function to find all occurrences of P in S


void KMPsearch(const string& S, const string& P) {
int n = S.length(); int m = P.length(); vector<int>
lps = buildLPS(P);

int i = 0; // index for S int j


= 0; // index for P

bool found = false; // flag to check if any pattern is found

cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"\n"; cout
<< "--------------------------------------------\n";
while (i < n) { if (P[j] == S[i]) {
i++; j++;
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

if (j == m)

{ found = true; cout << ">> Pattern found at index: " <<
(i - j) << " <<\n"; j = lps[j - 1]; // get the index from LPS array

} else if (i < n && P[j] != S[i]) { if (j


!= 0) { j = lps[j - 1]; // use the LPS
array
} else { i++;
}
}
}

if (!found) { cout << ">> No occurrences of the pattern


found. <<\n";
}

cout << "--------------------------------------------\n";


}

int main() {
string S = "ababcababcababc";
string P = "ababc"; KMPsearch(S, P); return
0;

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
The overall time complexity is: O(n + m) Space Complexity: The overall space
complexity is: O(m).

7. Learning Outcomes:

• Efficient String Matching:


You will understand how the KMP algorithm efficiently finds all occurrences of a
pattern P in a string S, avoiding redundant comparisons.
• LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix Suffix (LPS) array to
skip unnecessary comparisons, optimizing the search process.
• Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and space complexity,
understanding why KMP achieves linear time complexity O(n + m) with only O(m)
space overhead.
Experiment: 9

Student Name: Vikrant Chib UID: 22BCS50099


Branch: BE CSE Section: 22BCS630/B
Semester: 5th Date of Performance:25/10/24
Subject Name: AP _LAB 01 Subject Code: 22CSP-314

1.Aim:
Backtracking/Dynamic Programming: To demonstrate the concept of Backtracking and d ynamic
Programming.

2.Objective:
Your goal is to ind the number of ways to construct an array such that consecutive positions
containdifferent values.
Speci ically, we want to construct an array with elements such that each element between and ,
inclusive. We also want the irst and last elements of the arrayto be and .
Given , and , ind the number of ways to construct such an array. Since the answer may be large, only
ind it modulo .

3.Implementation/Code:
#include <iostream>
#include <vector>

using namespace std;

const long MOD = 1e9 + 7;

long countArray(int n, int k, int x) { //


Create two arrays for DP: f[i] and g[i]
vector<long> f(n + 1, 0); vector<long>
g(n + 1, 0);
// Base cases
f[2] = 1; g[2]
= 0;

// Fill DP arrays for (int i = 3; i <= n;


i++) { f[i] = (g[i - 1] + (k - 2) * f[i - 1])
% MOD; g[i] = ((k - 1) * f[i - 1]) %
MOD;
}

// Return the result based on x return


(x == 1) ? g[n] : f[n];
}

int main() { int n,


k, x; cin >> n >> k
>> x;

cout << countArray(n, k, x) << endl;

return 0;
}
4. Output:

Problem -2

1. Aim:
Given a chess board having N×N cells, you need to place N queens on the board in such a way that no
queen attacks any other queen.

2. Objective:
The objective is to solve the N-Queens problem, which involves placing N queens on an N×N
chessboard such that no two queens threaten each other. This means that no two queens can be placed in
the same row, column, or diagonal. The challenge is to ind all possible con igurations for placing the
queens on the board.

3. Code:
#include <iostream>

#include <vector> using

namespace std; class

NQueens { public:

NQueens(int n) : N(n) {

board.resize(N, vector<int>(N, 0));

}
void solve() {

placeQueens(0);

private:

int N;

vector<vector<int>> board;

void printBoard() {

for (const auto& row : board) {

for (int cell : row) { cout

<< (cell ? "Q " : ". ");

cout << endl;

cout << endl;

bool isSafe(int row, int col) { // Check this

column on upper side for (int i = 0; i < row;

i++) if (board[i][col]) return false; //

Check upper diagonal on left side for (int i =

row, j = col; i >= 0 && j >= 0; i--, j--) if

(board[i][j]) return false;


// Check upper diagonal on right side for

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

if (board[i][j]) return false; return true; } void

placeQueens(int row) {

if (row == N) {
printBoard();

return;

for (int col = 0; col < N; col++) { if (isSafe(row, col)) {

board[row][col] = 1; // Place queen placeQueens(row +

1); // Recur to place the next queen board[row][col] = 0;

// Backtrack

} } }};

int main() {

int N;

cout << "Enter the number of queens: ";

cin >> N;

NQueens queens(N);

queens.solve(); return

0;

}
4. Output:

5. Learning Outcome
i. Learn to solve optimization problems where constraints involve comparative values between
adjacent elements.

ii. Understand how to implement a two-pass algorithm to achieve the optimal solution in such
scenarios. iii. learn how to apply cumulative cost calculations in scenarios involving
variable constraints.
iv. They will understand how to optimize and calculate required values based on a progressive
increase in factors, such as the distance Marc must walk per cupcake.

v. This exercise will enhance problem-solving skills in handling scenarios with incremental
constraints and applying mathematical calculations effectively.
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

Experiment: 8

Student Name: Vikrant Chib UID: 22BCS50099


Branch: BE CSE Section:22BCS630/B
Semester: 5th Date of Performance:11/10/24
Subject Name: DAA LAB Subject Code: 22CSH-311

1. Aim: Develop a program and analyze complexity to find shortest paths in a graph with
positive edge weights using Dijkstra’s algorithm.

2. Objective: To implement and analyze the efficiency of Dijkstra’s algorithm for finding the
shortest paths in a graph with positive edge weights. The goal is to evaluate the algorithm's
time complexity based on the data structure used for the priority queue (e.g., binary heap
or Fibonacci heap).

3. Algorithm:
Step1:- Initialize:

• Create a distance array dist[] and set all values to infinity (∞) except for the source
node, which is set to 0.
• Use a priority queue (min-heap) to store nodes with their current known shortest
distance.

Step 2:- Push Source:

• Insert the source node into the priority queue with a distance of 0.

Step 3:- While Queue is Not Empty:

• Extract the node u with the minimum distance from the priority queue.
• For each neighboring node v of u, calculate the tentative distance to v through u.
• If this distance is smaller than the current distance in dist[v], update dist[v] and
insert v into the priority queue with the new distance.

Step 4:- Repeat:


DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

• Continue this process until the priority queue is empty.

Step 5:- Result:

• At the end, dist[] contains the shortest distance from the source node to all other
nodes.

4. Implementation/Code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

typedef pair<int, int> PII; // Pair to store (distance, vertex)

// Dijkstra's algorithm to find the shortest paths from a source node vector<int> dijkstra(int
source, const vector<vector<PII>>& graph, int V) { priority_queue<PII, vector<PII>,
greater<PII>> pq; // Min-heap priority queue
vector<int> dist(V, INT_MAX); // Initialize distances to infinity

dist[source] = 0; // Distance to the source is 0 pq.push({0, source});


// Push the source into the priority queue while (!pq.empty()) { int u =
pq.top().second; // Get the vertex with the
smallest distance pq.pop();

// Traverse all adjacent vertices of u for (const


auto& neighbor : graph[u]) { int v =
neighbor.second; int weight = neighbor.first;

// Relaxation step if (dist[u] + weight


< dist[v]) { dist[v] = dist[u] + weight;
pq.push({dist[v], v}); // Push updated distance to the priority queue
}
}
}
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

return dist; // Return the shortest distance to all vertices


}

int main() { int V = 5; // Number of


vertices vector<vector<PII>> graph(V);

// Adding edges (weight, vertex) graph[0].push_back({10,


1}); graph[0].push_back({3, 2}); graph[1].push_back({1,

3}); graph[2].push_back({4, 1}); graph[2].push_back({8, 3});


graph[2].push_back({2, 4}); graph[3].push_back({7, 4});

int source = 0; // Set the source node

// Run Dijkstra's algorithm vector<int> distances = dijkstra(source,


graph, V);
// Output the shortest distances from the source node cout <<
"Shortest distances from node " << source << ":\n"; for (int i = 0; i <
V; ++i) { cout << "Node " << i << " : " << distances[i] << "\n";
}

return 0;
}

5. Output:
DEPARTMENT OF
SCIENCE & ENGINEERING COMPUTER

6. Time Complexity:
Using Binary Heap: O((V + E) log V), where V is the number of vertices and E is the
number of edges.
Using Fibonacci Heap: O(E + V log V).

Space Complexity:
The overall space complexity of Dijkstra’s algorithm is O(V + E), where V is the number
of vertices and E is the number of edges.

7. Learning Outcomes:

1. Understanding of Dijkstra's Algorithm: You will learn how to implement and apply
Dijkstra’s algorithm to find the shortest paths in graphs with positive edge weights,
utilizing a priority queue for efficiency.
2. Time and Space Complexity Analysis: You will gain insights into analyzing the time
complexity (O((V + E) log V) using a binary heap) and space complexity (O(V + E)) of
the algorithm.
3. Graph Representation: You will understand how to represent graphs efficiently using
adjacency lists and handle shortest path problems with realworld applications.

You might also like