C++ program to find out the number of coordinate pairs that can be made

C++Server Side ProgrammingProgramming

Suppose, we are given 2n number of coordinates on a two-dimensional plane. The 2n coordinates are divided into two arrays coordA, and coordB. The coordinates are represented as integer pairs. Now we have to form coordinate pairs that will contain one point from coordA and one point from coordB. We can make pairs if and only if the x coordinate of the point from coordA is smaller than that of the point from coordB, and the y coordinate of the point from coordA is smaller than that of the point from coordB. We have to find out the number of pairs we can make, and a point cannot belong to multiple pairs.

So, if the input is like n = 3, coordsA = {{1, 3}, {2, 4}, {4, 3}}, coordsB = {{2, 2}, {4, 2}, {0, 2}}, then the output will be 1.

The only pair that can be made is (1, 3) and (0, 2).

To solve this, we will follow these steps −

Define an array chk of size: 100 initialized with 0
sort the array coordA
sort the array coordB
k := 0
for initialize i := n - 1, when i >= 0, update (decrease i by 1), do:
for initialize j := 0, when j < n, update (increase j by 1), do:
if chk[j] is same as 0 and first value of coordA[i] < second value of coordB[j] and second value of coordA[i] < first value of coordB[j], then:
chk[j] := 1
(increase k by 1)
Come out from the loop
print(k)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
#define N 100
void solve(int n, vector<pair<int,int>> coordA, vector<pair<int,int>>coordB){
   int i, j, k;
   int chk[100] = {0};
   sort(coordA.begin(),coordA.end());
   sort(coordB.begin(),coordB.end());
   k = 0;
   for(i = n - 1; i >= 0; i--) {
      for(j = 0; j < n; j++) {
         if(chk[j] == 0 && coordA[i].first < coordB[j].second && coordA[i].second < coordB[j].first) {
            chk[j] = 1;
            k++;
            break;
         }
      }
   }
   cout<< k;
}
int main() {
   int n = 3;
   vector<pair<int,int>> coordsA = {{1, 3}, {2, 4}, {4, 3}};
   vector<pair<int,int>> coordsB = {{2, 2}, {4, 2}, {0, 2}};
   solve(n, coordsA, coordsB);
   return 0;
}

Input

3, {{1, 3}, {2, 4}, {4, 3}}, {{2, 2}, {4, 2}, {0, 2}}

Output

1
raja
Updated on 25-Feb-2022 11:29:45

Advertisements