Aditya8daa Merged
Aditya8daa Merged
Aditya8daa Merged
Experiment: 8
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.
• Insert the source node into the priority queue with a distance of 0.
• 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.
• 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>
// 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
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
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>
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>
NQueens { public:
NQueens(int n) : N(n) {
}
void solve() {
placeQueens(0);
private:
int N;
vector<vector<int>> board;
void printBoard() {
placeQueens(int row) {
if (row == N) {
printBoard();
return;
// Backtrack
} } }};
int main() {
int N;
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
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
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
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.
3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)
• 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.
4. Implementation/Code:
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
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:
Experiment: 8
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.
• Insert the source node into the priority queue with a distance of 0.
• 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.
• 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>
// 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
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
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>
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>
NQueens { public:
NQueens(int n) : N(n) {
}
void solve() {
placeQueens(0);
private:
int N;
vector<vector<int>> board;
void printBoard() {
placeQueens(int row) {
if (row == N) {
printBoard();
return;
// Backtrack
} } }};
int main() {
int N;
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
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.
3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)
• 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.
4. Implementation/Code:
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
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:
Experiment: 8
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
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
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
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
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>
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>
NQueens { public:
NQueens(int n) : N(n) {
}
void solve() {
placeQueens(0);
private:
int N;
vector<vector<int>> board;
void printBoard() {
placeQueens(int row) {
if (row == N) {
printBoard();
return;
// Backtrack
} } }};
int main() {
int N;
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
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.
• Insert the source node into the priority queue with a distance of 0.
• 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.
• 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>
// 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
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
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.
3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)
• 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.
4. Implementation/Code:
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
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:
Experiment: 8
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
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
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given strings.
3. Algorithm:
Step 1: Build LPS Array (Longest Prefix Suffix)
• 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.
4. Implementation/Code:
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
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:
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>
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>
NQueens { public:
NQueens(int n) : N(n) {
}
void solve() {
placeQueens(0);
private:
int N;
vector<vector<int>> board;
void printBoard() {
placeQueens(int row) {
if (row == N) {
printBoard();
return;
// Backtrack
} } }};
int main() {
int N;
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
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.
• Insert the source node into the priority queue with a distance of 0.
• 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.
• 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>
// 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
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.