0% found this document useful (0 votes)
23 views35 pages

Ilovepdf Merged

Uploaded by

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

Ilovepdf Merged

Uploaded by

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

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment – 8(a)

Student Name: Tejas Atwal UID 22BCS15742


Branch: BE-CSE Section/Group: 622-A
Semester: 5 Date of Performance: 17/10/24
Subject Name: Advanced Programming Subject Code: 22CSP-314

1. Aim:
Problem 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
ccc calories he must walk at least 2j×c miles to maintain his weight.

2. Objective:
The provided code defines a function, `marcsCakewalk`, that calculates
the minimum total number of miles Marc needs to walk to burn the
calories from a list of cakes, given their calorie values. It first sorts the
calorie values in descending order and then computes the total miles by
multiplying each calorie value by 2i. The final result is printed in the
`main` function after reading the number of cakes and their respective
calorie counts.

3. Implementation/Code:
#include <bits/stdc++.h>
using namespace std;
long long marcsCakewalk(int calorie[], int n) {
sort(calorie, calorie + n, greater<int>());

long long total_miles = 0;


for(int i = 0; i < n; i++) {
total_miles += (1LL << i) * (long long)calorie[i];
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

return total_miles;
}
int main(){
int n;
cin >> n;
int calorie[40];
for(int i = 0; i < n; i++){
cin >> calorie[i];
}
long long result = marcsCakewalk(calorie, n);
cout << result;
return 0;
}

4. Output:

5. Time Complexity: O( N logn)

6. Space Complexity: O(n)


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

7. Learning Outcome:
1. Learn how sorting can impact problem-solving strategies by arranging
elements to maximize or minimize certain conditions.
2. Understand the usage of bitwise operations in practical scenarios like
exponential multiplication.
3. Develop an intuition for greedy algorithms where arranging input in a
certain order can lead to optimal solutions.
4. Manage basic I/O operations in C++.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment – 8(b)

Student Name: Tejas Atwal UID 22BCS15742


Branch: BE-CSE Section/Group: 622-A
Semester: 5 DateofPerformance: 17/10/24
Subject Name: Advanced Programming Subject Code: 22CSP-314

1. Aim:
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 of this code is to calculate the minimum number of candies
required to distribute to children based on their ratings while ensuring that
each child receives at least one candy and children with higher ratings than
their immediate neighbours receive more candies. It initializes an array to
track the candy count for each child, iterates through the ratings to assign
candies based on the given conditions, and finally sums up the total candies
distributed.

3. Algorithm:
 Read the number of elements n, allocate two arrays arr and candy, and
input n values into arr while initializing candy to 1 for each element.
 Iterate from the start to the end of the array, incrementing candy count for
each element if it's greater than the preceding element.
 Iterate from the end to the start of the array, adjusting the candy count to
ensure every element that's greater than the succeeding one has more
candy.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

 Sum all elements in the candy array using accumulate to determine the total
number of candies required.
 Print the total number of candies.

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

long long marcsCakewalk(int calorie[], int n) {


sort(calorie, calorie + n, greater<int>());
long long total_miles = 0;
for(int i = 0; i < n; i++) {
total_miles += (1LL << i) * (long long)calorie[i];
}
return total_miles;
}

int main(){

int n;
cin >> n;

int calorie[40];

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


cin >> calorie[i];
}
long long result = marcsCakewalk(calorie, n);
cout << result;

return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

5. Output:

6. Time Complexity: O(n)

7. Space Complexity: O(n)

8. Learning Outcome:
1. Understand applying greedy strategies for optimization problems.
2. Use C++ standard library functions like max for computational efficiency.
3. Learn how to efficiently manage and manipulate data in arrays.
4. Implement conditional checks for solving sequential decision problems.
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
Experiment-7
Student Name: Tejas Atwal UID: 22BCS15742
Branch: CSE Section/Group: IOT_622-A
th
Semester: 5 Date of Performance: 24-10-24
Subject Name: ADVANCED PROGRAMMING LAB-1
Subject Code: 22CSP-314

Problem 1-Breadth First Search

1. Aim: Implement a code to analyze the working of Breadth first serach in graphs.

2. Objective: Consider an undirected graph where each edge weighs 6 units. Each of
the nodes is labelled consecutively from 1 to n. You will be given a number of queries.
For each query, you will be given a list of edges describing an undirected graph.

3. Algorithm –
Initialization:
1. Create a distances vector to store the shortest distances from the source nodes to all other
nodes. Initialize all distances to -1 to indicate unvisited nodes.
2. Create a queue q to perform BFS.
3. Enqueue the source node s and set its distance to 0.
4. Dequeue the front node u from the queue.
5. Iterate through all neighbors v of node u:
▪ If v is unvisited (distance is -1):
▪ Set the distance to v as distances[u] + 1 (one more step from u).
▪ Enqueue v for further exploration.
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
4. Implementation/Code:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
public static List<Integer> bfs(int n, int m, List<List<Integer>> edges, int s) {

if (n < 1 || edges == null || edges.size() < 1 || s < 1) return null;

Set<Integer> [] tree = new Set[n];


for (List<Integer> edge : edges) {
int a = edge.get(0);
int b = edge.get(1);
if (tree[a-1] == null) {
tree[a-1] = new HashSet<Integer>();
}
tree[a-1].add(b);
if (tree[b-1] == null) {
tree[b-1] = new HashSet<Integer>();
}
tree[b-1].add(a);
}

List<Integer> res = new ArrayList<Integer>();

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


res.add(-1);
}
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
Set<Integer> root = tree[s-1];
if (root == null) return res;

Deque<Integer> queue = new LinkedList<Integer>();


for (Integer r : root) {
queue.add(r);
}
int height = 1;
boolean [] visited = new boolean [n];
visited[s-1] = true;
while (!queue.isEmpty()) {
Deque<Integer> queuen = new LinkedList<Integer>();
while (!queue.isEmpty()) {
int v = queue.poll().intValue();
if (!visited[v-1]) {
visited[v-1] = true;

if (v > s)
res.set(v-2, height*6);
else
res.set(v-1, height*6);
if (tree[v-1] != null) {
for (Integer r : tree[v-1]) {
queuen.add(r);
}
}
}
}
queue = queuen;
height++;
}
return res;
}

}
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING

5. Output

6. Time complexity: O(V + E), where V is the number of vertices (nodes) and E is the number of
edges in the graph

7. Learning outcomes
a. Learnt about breadth first serach algorithm.
b. Learnt about graph traversal.
c. Learnt how to analyze the time complexity for BFS.
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
Problem 2- Quickest way up

1. Aim: Implement a code to analyze the snake and ladder game by using quickest way up.

2. Objective:
• The game is played with a cubic die of 6 faces numbered 1 to 6.
• land on square 100 with the exact roll of the die. If moving the number rolled
would place the player beyond square 100 , no move is made.
• If a player lands at the base of a ladder, the player must climb the ladder.
Ladders go up only.
• If a player lands at the mouth of a snake, the player must go down the snake
and come out through the tail. Snakes go down only.

3. Algorithm-
While the queue is not empty:

1. Get the current queue size.


2. Process all nodes (positions) in the current level (using a loop with size as the limit):
• Dequeue the current position from the queue.
• If the current position is 100 (destination), return the minMoves.
• Loop through possible moves (1 to 6).
• Calculate the new position by adding the move to the current position.
• Skip positions beyond 100 or already visited positions.
• Check for ladders and snakes using the applyMove function.
• If a ladder is found, update the new position to the ladder's end (climb the ladder).
• If a snake is found, update the new position to the snake's head (slide down the
snake).
• Mark the new position as visited and add it to the queue.
3. Increment minMoves to represent one level deeper in the BFS search.

4. Implementation/code:
import java.io.*;

import java.math.*;

import java.security.*;

import java.text.*;
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
import java.util.*;

import java.util.concurrent.*;

import java.util.regex.*;

class Result {

public static int quickestWayUp(List<List<Integer>> ladders, List<List<Integer>> snakes) {

// Write your code here

boolean[] visited = new boolean[101];

visited[1] = true;

while (!queue.isEmpty()) {

int size = queue.size();

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

int currentPos = queue.poll();

if (currentPos == 100) {

return minMoves;

for (int move = 1; move <= 6; move++) {

int newPos = currentPos + move;

if (newPos > 100 || visited[newPos]) {

continue;

newPos = applyMove(newPos, ladders, snakes)

visited[newPos] = true;

queue.offer(newPos);
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
minMoves++;
}
return -1;

private static int applyMove(int newPos, List<List<Integer>> ladders, List<List<Integer>>


snakes) {
for (List<Integer> ladder : ladders) {

if (ladder.get(0) == newPos) {

return ladder.get(1);

for (List<Integer> snake : snakes) {

if (snake.get(0) == newPos) {

return snake.get(1);

}
return newPos;

}
DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
5. Output

6. Time complexity – O(V + E), where: V = number of vertices (positions) on the board (100) and E
= number of edges (connections)

7. Learning outcomes-
a. Understood the concept of BFS and its application in graph traversal.
b. Learnt how to implement BFS using a queue to explore nodes level by level.
c. Recognized the use of a visited array to prevent revisiting nodes.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment 9
Student Name: Tejas Atwal UID: 22BCS15742
Branch: CSE Section/Group: IOT-622-A
Semester: 5th Date of Performance: 22/10/2024
Subject Name: Advanced Programming Lab-1 Subject Code: 22CSP-314

Title - Backtracking/ Dynamic Programming

Problem-1

1. Aim:
To solve a 10*10 Crossword grid is provided to you, along with a set of words (or names
of places) which need to be filled into the grid. Cells are marked either + or -. Cells
marked with a - are to be filled with the word list.

2. Objective:
 To learn how to manipulate a two-dimensional grid structure to fill in words based
on specific constraints.
 To gain experience in developing algorithms that search for valid positions for words
horizontally and vertically within the grid.

3. Algorithm:
Initialize the Grid:
 Create a 2D character array grid of size 10x10.
 Populate grid with the characters from the input crossword list.

Prepare Word List:

 Split the input string words by semicolons (;) to create an array of words called
wordList.

Define a Recursive Function (solveCrossword):


 Create a recursive function solveCrossword(char[][] grid, String[] words, int
index) that:
o Base Case: If index is equal to the length of words, the crossword is
successfully filled, and return true.
o Iterate Over the Grid:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

 Loop through each cell in the grid.


 For each cell that contains a '-', attempt to place the word from
words[index]:
1. Check Horizontal Placement:

 Ensure that the word can fit horizontally from the current cell
without overlapping existing letters incorrectly.
 If placement is valid, temporarily place the word on the grid.
 Recursively call solveCrossword with the next index.
 If the recursive call returns true, the puzzle is solved; return true.
 If not, remove the word (backtrack) by resetting the affected cells.

2. Check Vertical Placement:

 Ensure that the word can fit vertically from the current cell.
 If placement is valid, temporarily place the word on the grid.
 Recursively call solveCrossword with the next index.
 If the recursive call returns true, the puzzle is solved; return true.
 If not, remove the word (backtrack) by resetting the affected cells.

Return Result:
 If solveCrossword returns true, convert the grid back to a list of strings and return
it as the result.
 If the puzzle cannot be solved, return an empty list or an indication of failure.

4. Implementation/Code: (Java)
public static List<String> crosswordPuzzle(List<String> crossword, String words) {
// Write your code here
char[][] grid = new char[10][10];
for (int i = 0; i < 10; i++) {
grid[i] = crossword.get(i).toCharArray();
}
String[] wordList = words.split(";");
solveCrossword(grid, wordList, 0);
List<String> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
result.add(new String(grid[i]));
}
return result;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

5. Output:

6. Time Complexity: O(n⋅m), where n is the number of words in wordlist and m is


the average length of the words.

7. Learning Outcomes:
 I learned how to implement a backtracking algorithm to solve constraint satisfaction
problems, specifically in the context of filling a crossword grid with given words.
This approach emphasizes the importance of exploring all possible configurations to
find a valid solution.
 I learned how to effectively represent a 2D grid using a character array, which allows
for easy manipulation of the grid while placing words. This demonstrates the utility of
data structures in solving complex problems.
 I learned the significance of checking both horizontal and vertical placements for
each word, ensuring that the constraints of the puzzle (such as neighboring words) are
respected. This highlights the importance of thorough validation in algorithm design.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem – 2

1. Aim:
The aim of studying the Fibonacci sequence is to understand its mathematical properties
and its applications in nature and various fields. By exploring how each term is derived
from the sum of the two preceding terms, we can appreciate its patterns and occurrences
in natural phenomena, such as the arrangement of leaves and flowers.

2. Objective:
 To learn the formal definition of the Fibonacci sequence and how it is generated
through recursive relationships.
 To investigate the mathematical properties of the Fibonacci sequence, including its
relation to the golden ratio and its growth patterns.

3. Algorithm:
 Initialization:
o Create an array dp of size n + 1 to store Fibonacci numbers.
o Set dp[0] = 0 (base case).
Set dp[1] = 1 (base case).
 Iterative Calculation:
o For each index i from 2 to n:
 Calculate the Fibonacci number at index i using the formula:
dp[i]=dp[i−1]+dp[i−2]
o This means the Fibonacci number at index i is the sum of the two preceding
numbers in the sequence.
 Return the Result:
o Return dp[n], which contains the Fibonacci number for the input n.

4. Implementation/Code: (Java)
public static int fibonacci(int n) {
// Complete the function.
int dp[] = new int[n+1];
dp[0] = 0;
dp[1] = 1;
for(int i=2; i<=n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

return dp[n];
}
5. Output:

6. Time Complexity:
O(n), where n represents the index in the Fibonacci sequence for which you want to
calculate the Fibonacci number.

7. Learning Outcomes:
 I learned how to apply dynamic programming to solve the Fibonacci sequence
problem efficiently, reducing the time complexity compared to the naive recursive
approach.
 I gained insights into how using an array to store previously computed Fibonacci
values helps avoid redundant calculations, showcasing the trade-off between time
and space complexity.
 I learned how an iterative approach can be more efficient than recursion for problems
with overlapping subproblems, demonstrating practical coding techniques for
performance optimization.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Complex Problems for Fast Learner’s


Course Name: Advance Programming Lab – I
Subject Code: - (22CSP-314/22ITP-314)

Student Name: Tejas Atwal UID: 22BCS15742


Branch: BE-CSE Section/Group: 622/A
Semester: 5th Date of Performance:22.10.24

Aim:
Trapping rainwater problem: Find the maximum amount of water that can be
trapped within a given set of bars where each bar’s width is 1 unit.

Code:

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

int trapRainWater(int height[], int n) {


int left = 0, right = n-1, left_max = 0, right_max = 0, trapped = 0;
while(left < right){
if(height[left] < height[right]){
if(height[left] >= left_max) left_max = height[left];
else trapped += left_max - height[left];
left++;
}
else{
if(height[right] >= right_max) right_max = height[right];
else trapped += right_max - height[right];
right--;
}
}
return trapped;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int main(){
int height[] = {7, 0, 4, 2, 5, 0, 6, 4, 0, 5};
int n = sizeof(height)/sizeof(height[0]);
cout << "The maximum amount of water that can be trapped is: " << trapRainWater(height,
n) << endl;
}

Ques 2:

You are given a 0-indexed integer array stations of length n, where stations[i] represents
the number of power stations in the ith city. Each power station can provide power to
every city in a fixed range. In other words, if the range is denoted by r, then a power
station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1.
Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7. The power of
a city is the total number of power stations it is being provided power from. The
government has sanctioned building k more power stations, each of which can be built in
any city, and have the same range as the pre-existing ones. Given the two integers r and k,
return the maximum possible minimum power of a city, if the additional power stations
are built optimally.

Code:

#include <bits/stdc++.h>
using namespace std;
const int MAX = 100005;

long long computeInitialPower(int stations[], int power[], int n, int r) {


long long prefix[MAX] = {0};
for(int i=0;i<n;i++) prefix[i+1] = prefix[i] + stations[i];
for(int i=0;i<n;i++)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

{
int L = max(0, i - r);
int R = min(n-1, i + r);
power[i] = prefix[R+1] - prefix[L];
}
return 0;
}

bool isPossible(long long mid, int power[], int n, int r, long long k) {
long long add_diff[MAX] = {0}, current_add = 0, additions = 0;
for(int i=0;i<n;i++) {
current_add += add_diff[i];
long long total = power[i] + current_add;
if(total < mid){
long long need = mid - total;
additions += need;
if(additions > k) return false;
int pos = min(n-1, i + r);
int L = max(0, pos - r);
int R = min(n-1, pos + r);
add_diff[L] += need;
if(R+1 < n) add_diff[R+1] -= need;
current_add += need;
}
}
return additions <= k;
}

long long maximizeMinimumPower(int stations[], int n, int r, long long k) {


int power[MAX];
computeInitialPower(stations, power, n, r);
long long left = 0, right = *max_element(power, power+n) + k;
while(left < right){
long long mid = left + (right +1 - left)/2;
if(isPossible(mid, power, n, r, k)) left = mid;
else right = mid -1;
}
return left;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int main(){
// Example 1
{
int stations[] = {1,2,4,5,0};
int n = 5, r = 1;
long long k = 2;
cout << "Example 1 Output: " << maximizeMinimumPower(stations, n, r, k) << endl;
}
// Example 2
{
int stations[] = {4,4,4,4};
int n = 4, r = 0;
long long k = 3;
cout << "Example 2 Output: " << maximizeMinimumPower(stations, n, r, k) << endl;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

3. You are given two strings s and t. You are allowed to remove any number of
characters from the string t. The score of the string is 0 if no characters are removed from
the string t, otherwise: Let left be the minimum index among all removed characters. Let
right be the maximum index among all removed characters. Then the score of the string
is right - left + 1. Return the minimum possible score to make t a subsequence of s.
A subsequence of a string is a new string that is formed from the original string by
deleting some (can be none) of the characters without disturbing the relative positions of
the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

CODE:-

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

const int MAX = 100005;

// Compute the prefix array: prefix[i] stores the earliest position in s where t[0..i] is a subsequence
void computePrefix(const char* s, int n, const char* t, int m, int prefix[]) {
int p = 0;
for(int i = 0; i < m; ++i){
while(p < n && s[p] != t[i]) p++;
if(p < n){
prefix[i] = p;
p++;
}
else{
for(int j = i; j < m; ++j) prefix[j] = -1;
break;
}
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

// Compute the suffix array: suffix[i] stores the latest position in s where t[i..m-1] is a subsequence
void computeSuffix(const char* s, int n, const char* t, int m, int suffix[]) {
int p = n-1;
for(int i = m-1; i >=0; --i){
while(p >=0 && s[p] != t[i]) p--;
if(p >=0){
suffix[i] = p;
p--;
}
else{
for(int j = i; j >=0; --j) suffix[j] = -1;
break;
}
}
}

int main(){
// Disable synchronization for faster I/O
ios::sync_with_stdio(false);
cin.tie(0);

// Define Test Cases


struct TestCase {
string s;
string t;
int expected_output;
};

TestCase test_cases[] = {
{"abacaba", "bzaa", 1},
{"cde", "xyz", 3}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int num_tests = sizeof(test_cases)/sizeof(TestCase);


for(int tc = 0; tc < num_tests; ++tc){
string s_str = test_cases[tc].s;
string t_str = test_cases[tc].t;
int expected = test_cases[tc].expected_output;

const char* s = s_str.c_str();


const char* t = t_str.c_str();
int n = s_str.length();
int m = t_str.length();

int prefix[MAX], suffix_arr[MAX];


memset(prefix, -1, sizeof(prefix));
memset(suffix_arr, -1, sizeof(suffix_arr));

computePrefix(s, n, t, m, prefix);
computeSuffix(s, n, t, m, suffix_arr);

// Check if t is already a subsequence of s


if(prefix[m-1] != -1){
cout << "Test Case " << tc+1 << " Output: " << 0 << "\n";
continue;
}

// Find the minimum window to remove


int ans = m;
int r =0;
for(int l =0; l < m; ++l){
if(prefix[l-1] == -1 && l !=0) continue;
while(r < m){
if(suffix_arr[r] != -1 && (l ==0 || suffix_arr[r] > prefix[l-1])){
break;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

r++;
}
if(r == m) break;
ans = min(ans, r - l +1);
}

// If ans wasn't updated, it means removing all characters is necessary


if(ans == m && (prefix[m-1] == -1)){
ans = m;
}

4. You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three
types of queries: For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in
nums1 from index l to index r. Both l and r are 0-indexed. For a query of type 2, queries[i] = [2, p, 0]. For
every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p. For a query of type 3, queries[i] = [3, 0, 0].
Find the sum of the elements in nums2.Return an array containing all the answers to the third type queries.

Code:-

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 100005;
struct SegmentTree {
int tree[4 * MAX];
bool lazy[4 * MAX];
int n;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

void init(int size) {


n = size;
memset(tree, 0, sizeof(tree));
memset(lazy, 0, sizeof(lazy));
}
void build(int idx, int l, int r, int nums1[]) {
if(l == r) {
tree[idx] = nums1[l];
return;
}
int mid = (l + r) / 2;
build(2*idx, l, mid, nums1);
build(2*idx+1, mid+1, r, nums1);
tree[idx] = tree[2*idx] + tree[2*idx+1];
}
void push(int idx, int l, int r) {
if(lazy[idx]) {
int mid = (l + r) / 2;
tree[2*idx] = (mid - l +1) - tree[2*idx];
lazy[2*idx] ^= 1;
tree[2*idx+1] = (r - mid) - tree[2*idx+1];
lazy[2*idx+1] ^= 1;
lazy[idx] = 0;
}
}
void update(int idx, int l, int r, int L, int R) {
if(R < l || L > r) return;
if(L <= l && r <= R) {
tree[idx] = (r - l +1) - tree[idx];
lazy[idx] ^= 1;
return;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

push(idx, l, r);
int mid = (l + r) / 2;
update(2*idx, l, mid, L, R);
update(2*idx+1, mid+1, r, L, R);
tree[idx] = tree[2*idx] + tree[2*idx+1];
}
int query(int idx, int l, int r, int L, int R) {
if(R < l || L > r) return 0;
if(L <= l && r <= R) return tree[idx];
push(idx, l, r);
int mid = (l + r) / 2;
return query(2*idx, l, mid, L, R) + query(2*idx+1, mid+1, r, L, R);
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int nums1[MAX];
for(int i =0; i < n; i++) {
cin >> nums1[i];
}
ll nums2[MAX];
for(int i =0; i < n; i++) {
cin >> nums2[i];
}
SegmentTree st;
st.init(n);
st.build(1, 0, n-1, nums1);
ll total_ones = st.query(1, 0, n-1, 0, n-1);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

ll sum_nums2 = 0;
for(int i =0; i < n; i++) {
sum_nums2 += nums2[i];
}
int q;
cin >> q;
ll *output = new ll[q];
int output_size = 0;
for(int i =0; i < q; i++) {
int type, a, b;
cin >> type >> a >> b;
if(type == 1){
ll ones_before = st.query(1, 0, n-1, a, b);
st.update(1, 0, n-1, a, b);
ll range_length = b - a +1;
ll ones_after = range_length - ones_before;
total_ones += (ones_after - ones_before);
}
else if(type == 2){
ll p = a;
sum_nums2 += p * total_ones;
}
else if(type ==3){
output[output_size++] = sum_nums2;
}
}
cout << "[";
for(int i =0; i < output_size; i++){
cout << output[i];
if(i != output_size -1) cout << ",";
}
cout << "]\n";
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

OUTPUT

5. You are given an integer array nums and two integers minK and maxK. A
fixed-bound subarray of nums is a subarray that satisfies the following conditions: The
minimum value in the subarray is equal to minK. The maximum value in the subarray is
equal to maxK. Return the number of fixed-bound subarrays.A subarray is a contiguous
part of an array.

CODE:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int n;
cin >> n;
int nums[100005];
for(int i =0; i < n; i++) cin >> nums[i];
int minK, maxK;
cin >> minK >> maxK;
ll result = 0;
int last_min = -1, last_max = -1, last_invalid = -1;
for(int i =0; i < n; i++){
if(nums[i] < minK || nums[i] > maxK){
last_invalid = i;
}
if(nums[i] == minK){
last_min = i;
}
if(nums[i] == maxK){
last_max = i;
}
int current_min = min(last_min, last_max);
if(current_min > last_invalid){
result += (current_min - last_invalid);
}
}
cout << result;
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

6. - Given an array of integers heights representing the histogram's bar height


where the width of each bar is 1, return the area of the largest rectangle in the histogram.

CODE:

#include <bits/stdc++.h>
using namespace std;
// Function to calculate the largest rectangle area in a histogram
long long largestRectangleArea(vector<int>& heights) {
stack<int> st; // Stack to store indices
heights.push_back(0); // Append a zero to handle remaining bars
int n = heights.size();
long long max_area = 0;

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


while(!st.empty() && heights[i] < heights[st.top()]) {
int top = st.top();
st.pop();
long long height = heights[top];
long long width = st.empty() ? i : (long long)(i - st.top() - 1);
max_area = max(max_area, height * width);
}
st.push(i);
}
return max_area;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cout << "Enter the number of histogram bars: ";
cin >> n;

vector<int> heights(n);
cout << "Enter the heights of the histogram bars separated by space:\n";
for(int i = 0; i < n; i++) {
cin >> heights[i];
}
long long result = largestRectangleArea(heights);
cout << "The area of the largest rectangle in the histogram is: " << result << "\n";
return 0;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

OUTPUT

7. A path in a binary tree is a sequence of nodes where each pair of adjacent


nodes in the sequence has an edge connecting them. A node can only appear in the
sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.

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

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
int max_sum;
Solution() : max_sum(INT32_MIN) {}
int maxPathSumHelper(TreeNode* root) {
if (root == nullptr) return 0;
int left = max(maxPathSumHelper(root->left), 0);
int right = max(maxPathSumHelper(root->right), 0);
int current_max = root->val + left + right;
max_sum = max(max_sum, current_max);
return root->val + max(left, right);
}

int maxPathSum(TreeNode* root) {


maxPathSumHelper(root);
return max_sum;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int main(){
ios::sync_with_stdio(false);
cin.tie(0);

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);

Solution sol;
int result = sol.maxPathSum(root);

cout << "The maximum path sum of the binary tree is: " << result << "\n";

delete root->left;
delete root->right;
delete root;

return 0;
}

OUTPUT:

You might also like