C++程式中檢查數字是否位於N個L-R範圍內的查詢


在這個問題中,我們得到一個二維矩陣`arr[][2]`,它包含n個範圍(L, R),L-R。以及Q個查詢,每個查詢包含一個整數值。我們的任務是建立一個程式來解決這些查詢,以檢查數字是否位於N個L-R範圍內。

問題描述 − 在這裡,我們解決每個查詢,使得查詢的每個元素都位於任何一個範圍內。

範圍之間不能重疊。

讓我們來看一個例子來理解這個問題:

輸入

arr[n][2] = { {5, 7}, {1, 3}, {9, 12} } n = 3 Q = 2, query = {10, 4}

輸出

Yes
No

解釋

解決這個問題的一個簡單方法是解決每個查詢,並找到元素所在的範圍。如果它位於任何一個範圍內,則返回true,否則返回false。根據範圍值對矩陣進行排序可以有所幫助。

演算法

步驟1 − 按行對矩陣進行排序,即根據範圍排序。

步驟2 − 迴圈 i -> 0 到 Q,針對所有查詢。

步驟2.1 − 如果元素位於任何一個範圍內,即 (arr[i][0] <= q && arr[i][1] >= q) -> 返回true。

程式說明了我們解決方案的工作原理:

示例

 線上演示

#include <iostream>
using namespace std;
bool isPresent(int arr[][2], int n, int element){
   for(int i = 0; i < n; i++){
      if(arr[i][0] <= element && arr[i][1] >= element )
      return true;
   }
   return false;
}
void solveQueries_Range(int arr[][2], int n, int Q, int query[]){
   int temp[2];
   for(int j = 0; j < (n - 1); j++){
      for(int k = (j + 1); k < n; k++)
      if(arr[j][0] > arr[k][0]){
         temp[0] = arr[k][0]; temp[1] = arr[k][1];
         arr[k][0] = arr[j][0]; arr[k][1] = arr[j][1];
         arr[j][0] = temp[0]; arr[j][1] = temp[1];
      }
   }
   for(int i = 0; i < Q; i++ ){
      if(isPresent(arr, n, query[i]))
         cout<<"For Query "<<(i + 1)<<": The number "<<query[i]<<" lies in the range\n";
      else
         cout<<"For Query "<<(i + 1)<<": The number "<<query[i]<<" does not lie in the range\n";
   }
}
int main(){
   int arr[][2] = { {5, 7}, {1, 3}, {9, 12} };
   int n = 3;
   int Q = 2;
   int query[] = { 10, 4 };
   solveQueries_Range(arr, n, Q, query);
   return 0;
}

輸出

For Query 1: The number 10 lies in the range
For Query 2: The number 4 does not lie in the range

更新於:2020-12-22

155 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告