// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return total
// number of intersections
int FindIntersection(pair<int, int> type1[], int n,
pair<int, int> type2[], int m)
{
// Maximum possible number
// of intersections
int ans = n * m;
vector<int> start, end;
for (int i = 0; i < n; i++) {
// Store all starting
// points of type1 ranges
start.push_back(type1[i].first);
// Store all endpoints
// of type1 ranges
end.push_back(type1[i].second);
}
sort(start.begin(), start.end());
sort(end.begin(), end.end());
for (int i = 0; i < m; i++) {
// Starting point of type2 ranges
int L = type2[i].first;
// Ending point of type2 ranges
int R = type2[i].second;
// Subtract those ranges which
// are starting after R
ans -= (start.end() -
upper_bound(start.begin(), start.end(), R));
// Subtract those ranges which
// are ending before L
ans -=
(upper_bound(end.begin(), end.end(), L - 1)
- end.begin());
}
return ans;
}
// Driver Code
int main()
{
pair<int, int> type1[] =
{ { 1, 2 }, { 2, 3 }, { 4, 5 }, { 6, 7 } };
pair<int, int> type2[] =
{ { 1, 5 }, { 2, 3 }, { 4, 7 }, { 5, 7 } };
int n = sizeof(type1) / (sizeof(type1[0]));
int m = sizeof(type2) / sizeof(type2[0]);
cout << FindIntersection(type1, n, type2, m);
return 0;
}