Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Queries to return the absolute difference between Lth smallest number and the R-th smallest number in C++
In this tutorial, we will be discussing a program to find queries to return the absolute difference between L-th smallest number and the R-th smallest number.
For this we will be provided with an array containing integers and Q queries. Our task is to find the absolute difference between the indices of Lth smallest and Rth smallest values.
Example
#include <bits/stdc++.h>
using namespace std;
//returning the result of a query
int respondingQuery(pair<int, int> arr[], int l, int r) {
int result = abs(arr[l - 1].second - arr[r - 1].second);
return result;
}
//implementing the queries
void calcDifference(int givenarr[], int a, int q[][2], int b){
pair<int, int> arr[a];
for (int i = 0; i < a; i++) {
arr[i].first = givenarr[i];
arr[i].second = i;
}
sort(arr, arr + a);
for (int i = 0; i < b; i++)
cout << respondingQuery(arr, q[i][0], q[i][1]) <<
endl;
}
int main() {
int arr[] = { 1, 7, 4, 2, 8};
int arraySize = sizeof(arr) / sizeof(arr[0]);
int query[][2] = { { 2, 7 }, { 4, 8 }, { 1, 2 }, { 8, 1 }};
int querySize = sizeof(query) / sizeof(query[0]);
calcDifference(arr, arraySize, query, querySize);
return 0;
}
Output
3 32763 3 32764
Advertisements