Minimum Number of Arrows to Burst Balloons in C++

C++Server Side ProgrammingProgramming

Suppose there are few spherical balloons spread in two-dimensional space. For each balloon, there are the start and end coordinates of the horizontal diameter. Start is always smaller than end. There will be at most 104 balloons. One arrow can be shot up exactly vertically from different points along the x-axis. A balloon whose position is xstart to xend bursts by an arrow shot at x if xstart = x = xend. There is no limit to the number of arrows that can be shot. Assume that an arrow once shot keeps travelling up infinitely. We have to find the minimum number of arrows that must be shot to burst all balloons. So if the input is like [[10,16],[2,8], [1,6], [7,12]], then the output will be 2. So if we shoot from x = 6, then it will burst [2,8] and [1,6], and another balloon from x = 11 to burst the rest.

To solve this, we will follow these steps −

  • Define a method called intersect() to check whether the positions are intersecting or not

  • Another method manipulate() to manipulate the range after taking the range of all intersecting balloons

  • The actual method is taking the balloon positions as pos

  • sort the pos array based on the end positions

  • n := number of balloons, if n is 0, then return 0

  • currEnd := end position of the first entry of pos after soring

  • cnt := 1

  • for i in range 1 to n – 1

    • if currEnd < start position of pos[i], then increase count by 1, and currEnd := ending position of pos[i]

  • return count

Let us see the following implementation to get better understanding

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool intersect(vector <int>& a, vector <int>& b){
      return a[1] >= b[0];
   }
   static bool cmp(vector <int>& a, vector <int>& b){
      return a[1] < b[1];
   }
   void manipulate(vector <int>& a, vector <int>& b){
      a[0] = min(a[0], b[0]);
      a[1] = max(a[1], b[1]);
   }
   int findMinArrowShots(vector<vector<int>>& points) {
      sort(points.begin(), points.end(), cmp);
      int n = points.size();
      if(!n) return 0;
      int currEnd = points[0][1];
      int cnt = 1;
      for(int i = 1; i < n; i++){
         if(currEnd < points[i][0]){
            cnt++;
            currEnd = points[i][1];
         }
      }
      return cnt;
   }
};
main(){
   vector<vector<int>> v = {{10,16},{2,8},{1,6},{7,12}};
   Solution ob;
   cout << (ob.findMinArrowShots(v));
}

Input

[[10,16],[2,8],[1,6],[7,12]]

Output

2
raja
Published on 04-Mar-2020 06:46:05
Advertisements