
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ code to count number of unread chapters
Suppose we have an array of pairs P. Where P[i] is in the form (l, r), and have another number k. Consider we are going to read a book with n chapters. so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. We have read some pages and marked the page with number k as the first page which was not read. We have to find the number of chapters we have not completely read yet. P[i] represents the chapter page numbers range.
So, if the input is like P = [[1, 3], [4, 7], [8, 11]]; k = 4, then the output will be 2, because we have read the first chapter, another two chapters are there to read.
Steps
To solve this, we will follow these steps −
n := size of P for initialize i := 1, when i <= n, update (increase i by 1), do: if k >= P[i - 1, 0] and k <= P[i - 1, 1], then: return n - i + 1 return 0
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<vector<int>> P, int k){ int n = P.size(); for (int i = 1; i <= n; i++){ if (k >= P[i - 1][0] && k <= P[i - 1][1]) return n - i + 1; } return 0; } int main(){ vector<vector<int>> P = { { 1, 3 }, { 4, 7 }, { 8, 11 } }; int k = 4; cout << solve(P, k) << endl; }
Input
{ { 1, 3 }, { 4, 7 }, { 8, 11 } }, 4
Output
2
- Related Articles
- C++ code to count number of weight splits of a number n
- C++ code to count number of notebooks to make n origamis
- C++ code to count number of even substrings of numeric string
- C++ code to count number of packs of sheets to be bought
- C++ code to count number of times stones can be given
- C++ code to count number of lucky numbers with k digits
- C++ code to count number of operations to make two arrays same
- C++ code to count number of dice rolls to get target x
- C++ code to count volume of given text
- C++ code to count local extrema of given array
- How to add video chapters in YouTube video description
- 8085 code to convert binary number to ASCII code
- C++ code to count who have declined invitation
- C++ code to count ways to form reconnaissance units
- C++ code to count operations to make array sorted
