Skip to main content

C++ Day 39

  C++ Day 39 STL Containers (Deep Understanding & Real Usage) Till now, you already know arrays, vectors, loops, and STL algorithms. Today, we go one step deeper and understand STL containers , which are the backbone of modern C++ programming. In real projects and competitive coding, choice of container matters a lot. 1. What are STL Containers? STL containers are data structures provided by C++ to store data efficiently. They handle: memory management resizing element access performance optimization You focus on logic , not memory handling. 2. Categories of STL Containers STL containers are mainly divided into: Sequence Containers Associative Containers Unordered Containers Container Adapters 3. Sequence Containers These store data in sequence . 3.1 Vector Most used container in C++. vector< int > v; Key Features: Dynamic size Contiguous memory Fast random access Slower insertion in middle Example: v. push_...

C++ Day 37

 

Here’s C++ Day 37 with lots of rich, structured content so your daily practice stays meaningful.
This includes:
✔ Concepts
✔ Problems
✔ Code templates
✔ Mini-projects
✔ Debug tasks
✔ Interview-style challenges


πŸš€ C++ Day 37 – Advanced Mixed Practice (Deep Dive Edition)


1️⃣ Concept of the Day — “Bitmasking + DP + Greedy Hybrids”

Many advanced contest problems combine bit operations, DP, and greedy pruning.

πŸ‘‰ Key Points

  • Use bitmasks to represent subsets.

  • Use greedy heuristics to prune DP states.

  • Use __builtin_popcountll() for fast operations.

  • Precompute masks for speed.

⭐ Example Pattern

for (int mask = 0; mask < (1<<n); mask++) { int bits = __builtin_popcount(mask); dp[mask] = ...; }

2️⃣ Quick Practice Problems (with difficulty)

Try to solve these after studying the concept:

(A) Easy — "Count Bits in Ranges"

Given a range [l, r], count total number of 1-bits in all numbers.


(B) Medium — "Smallest Missing Bitmask Value"

Given array of integers (≤ 1e6), find the smallest value not representable as bitwise-AND of some subarray.


(C) Hard — “Maximize Score with K Picks + Bitmask States”

You have n coins with a[i] values and can choose exactly k coins.
Score = sum( chosen ) AND xor( chosen ).
Maximize score.
Constraint: n ≤ 1e5.

(Hint: use greedy + pruning on top bits)


3️⃣ Debugging Task (You must fix it)

This code tries to compute LIS but gives wrong output:

vector<int> lis; for (int i = 0; i < n; i++) { auto it = lower_bound(lis.begin(), lis.end(), arr[i], greater<int>()); if (it == lis.end()) lis.push_back(arr[i]); else *it = arr[i]; } cout << lis.size();

❌ What’s wrong?

  • Compares incorrectly for LDS/LIS

  • Should use:

    • lower_bound for LIS

    • upper_bound for some variants

  • OR use reverse comparator properly

Fix it as part of day 37.


4️⃣ Short Topic – “Prefix Tricks for DP”

Useful in problems with large ranges:

TrickUse
Prefix maxFor DP like knapsack variants
Prefix ANDTo track decreasing AND intervals
Prefix XORFor fast queries

Example:

vector<int> px(n+1); for(int i=1;i<=n;i++) px[i] = px[i-1] ^ arr[i];

5️⃣ Mini Project – “Meet-in-the-middle subset apps”

Problem:
Given n ≤ 40, find the number of subsets with sum ≤ W.

Plan:

  • Split array in two halves.

  • Generate all subset sums.

  • Sort one half.

  • For each sum in first half, binary search in second.

Skeleton:

void gen(vector<int>& arr, vector<long long>& out) { int n = arr.size(); for(int mask=0; mask < (1<<n); mask++) { long long sum = 0; for(int i=0;i<n;i++) if(mask&(1<<i)) sum += arr[i]; out.push_back(sum); } }

Finish it as exercise.


6️⃣ Interview Problem — “Minimum Removal Cost to Make Array Good”

Array is good if a[i] ≤ i.
Each removal costs a[i].
Find minimum cost.

Hint: Greedy + priority queue.


7️⃣ Competitive Problem — “Maximum Path Sum in Tree with State”

You get a tree with value on nodes.
You choose a path, but you can skip at most one value on the path (set one node’s value = 0).

Solve using:

  • DFS + DP states

  • State 0 = no skip used

  • State 1 = skip used


8️⃣ Code Template (Day 37 Standard)

#include <bits/stdc++.h> using namespace std; #define int long long #define all(x) x.begin(), x.end() int32_t main(){ ios::sync_with_stdio(false); cin.tie(nullptr); // Day 37 Starter Template int n; cin >> n; vector<int> arr(n); for(int &x : arr) cin >> x; // Write your code here return 0; }

Comments

Popular posts from this blog

C++ Day 35

  C++ Day 34: Layout Layouts (Part 2) We’ll cover: Constructer Layout Adjuster Layout Decorator Layout practise Task πŸ”Ή 1. developer form (creational) used to make compound objects measure away step ✅ employ case: you need to form associate in nursing aim (like amp pizza pie calculator house) with elective parameters example: cpp copy edit class calculator {     train Methodor gpu ram; public:     family developer {         train Methodor gpu ram;     public:         developer setcpu(string c) { Methodor = c; take *this; }         developer setgpu(string g) { gpu = g; take *this; }         developer setram(string r) { run = r; take *this; }         calculator Construct() {             take Calculater(cpu gpu ram);         }     };     Calculater(string snow train m train r) : cpu(c) gp...

C++ Day 33

  C++ Day 33: Smart Pointers & Memory Management πŸ”Ή 1. wherefore forward pointers in c++ hand-operated green / cancel is error-prone: memory leaks 🧠 double deletes ❌ dangling pointers πŸ’₯ smart pointers care store mechanically exploitation raii (Supply skill is initialization) πŸ”Ή ii. Types of Smart Pointers in C++ ✅ std::unique_ptr Sole ownership of a Supply. Cannot be copied. Automatically deletes the Supply when it goes out of scope. cpp Copy Edit #include  unique_ptr ptr1 = make_unique(10); cout << *ptr1 << endl; // 10 You can transfer ownership: cpp Copy Edit unique_ptr ptr2 = move(ptr1); ✅ std::shared_ptr Shared ownership multiple shared_ptrs can point to the same object. Uses reference counting to track how many owners. cpp Copy Edit shared_ptr p1 = make_shared(100); shared_ptr p2 = p1;  // Reference count = 2 When count goes to 0 memory is released. ✅ std::weak_ptr Non-owning reference to a shared_ptr-managed object. Used to break cyclic references ...

CSES Increasing Subsequence solution

 You are given an array containing  n n n integers. Your task is to determine the longest increasing subsequence in the array, i.e., the longest subsequence where every element is larger than the previous one. A subsequence is a sequence that can be derived from the array by deleting some elements without changing the order of the remaining elements. Input The first line contains an integer n n n : the size of the array. After this there are n n n integers x 1 , x 2 , … , x n x_1,x_2,\ldots,x_n x 1 ​ , x 2 ​ , … , x n ​ : the contents of the array. Output Print the length of the longest increasing subsequence. Constraints 1 ≤ n ≤ 2 ⋅ 1 0 5 1 \le n \le 2 \cdot 10^5 1 ≤ n ≤ 2 ⋅ 1 0 5 1 ≤ x i ≤ 1 0 9 1 \le x_i \le 10^9 1 ≤ x i ​ ≤ 1 0 9 Example Input: 8 7 3 5 3 6 2 9 8 Output: 4 #include < bits / stdc ++. h > using namespace std ; void solve (){ int n ; cin >> n ; vector <int> arr ( n ); for ( int i = 0 ; i < n ; i ++)...