ให้เมทริกซ์ 2 มิติ arr[][2] แทน n ช่วง (L, R) และ Q คำถาม แต่ละคำถามเป็นตัวเลข ต้องการตรวจสอบว่าตัวเลขอยู่ในช่วงไหนช่วงหนึ่ง (ช่วงไม่ทับซ้อนกัน)
ตัวอย่าง: arr = {{5,7},{1,3},{9,12}}, queries = {10,4} 10 อยู่ใน [9,12] → Yes, 4 ไม่อยู่ช่วงไหน → No
อัลกอริทึม
- เรียงช่วงตามค่า L
- แต่ละคำถาม: วนตรวจสอบทุกช่วง ถ้า L <= x <= R → Yes
- หรือใช้ Binary Search เพราะช่วงไม่ทับซ้อนและเรียงแล้ว
ตัวอย่างโค้ด C++
#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[]) {
// เรียงช่วงตามค่าเริ่มต้น
for (int j = 0; j < n-1; j++)
for (int k = j+1; k < n; k++)
if (arr[j][0] > arr[k][0])
swap(arr[j][0], arr[k][0]), swap(arr[j][1], arr[k][1]);
for (int i = 0; i < Q; i++) {
cout << "Query " << i+1 << ": The number " << query[i]
<< (isPresent(arr, n, query[i]) ? " lies in the range" : " does not lie in the range")
<< '\n';
}
}
int main() {
int arr[][2] = {{5,7},{1,3},{9,12}};
int n = 3, Q = 2, query[] = {10, 4};
solveQueries_Range(arr, n, Q, query);
return 0;
}
เอาต์พุต
Query 1: The number 10 lies in the range Query 2: The number 4 does not lie in the range