Klee’s Algorithm (Length Of Union Of Segments of a line) in C++


In this tutorial, we are going to write a program that finds the length of union of segments of a line.

We are given starting and ending points of the line segment and we need to find the length of union of segments of the line.

The algorithm that we are going to use is called klee's algorithm.

Let's see the steps to solve the problem.

  • Initialise the array with coordinates of all the segments.
  • Initialise a vector called points with double the size of segments array.
  • Iterate over the segments array.
    • Fill the values of points array at index i * 2 with the first point of the current segment and false.
    • Fill the values of points array at index i * 2 + 1 with the second point of the current segment and false.
  • Sort the points array.
  • Iterate over the points array with a counter variable.
    • If the counter is greater than 0, then add the first points of i and i - 1 to the result.
    • Decrement the counter if there is second point else increment it.
  • Return the result.

Example

Let's see the code.

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int segmentUnionLength(const vector<pair <int,int>> &segments) {
   int n = segments.size();
   vector<pair<int, bool>> points(n * 2);
   for (int i = 0; i < n; i++) {
      points[i*2] = make_pair(segments[i].first, false);
      points[i*2 + 1] = make_pair(segments[i].second, true);
   }
   sort(points.begin(), points.end());
   int result = 0, count = 0;
   for (int i = 0; i < n * 2; i++){
      if (count) {
         result += points[i].first - points[i-1].first;
      }
      points[i].second ? count-- : count++;
   }
   return result;
}
int main() {
   vector<pair<int,int>> segments;
   segments.push_back(make_pair(1, 3));
   segments.push_back(make_pair(2, 7));
   segments.push_back(make_pair(6, 12));
   segments.push_back(make_pair(13, 5));
   cout << segmentUnionLength(segments) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

6

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements