algorithm - Check if a number exists in a given set of ranges -
Assume that a set of our N Series, (A1, B1), (A2, B2) (A3, B3) .. (A, BN), where A indicates the starting point and BE represents the end point of a boundary. (AI, BI positive Intijrs are)
How do we use binary search, if a given integer, X say, N present in at least one N range of?
My approach:
-
Sort the ranges by the x coordinate and then y-coordinate.
-
The smallest X-coordinate is bigger or equal to X.
-
Check if the range is satisfied or not.
-
If yes, we have a solution.
Now, if there is no X in that category, what should my next step be?
Or, should the solution be completely different?
What is the description of your problem is that your
pairs as(a1, b1) a), (A2, B-2) whereis AX at the beginning of classbx finished now you are given a number Isn and you want to find that the number is in any category.
sort before then implement the merger in overlapping categories and binary search:#include & lt; Iostream & gt; # Include & lt; Algorithm & gt; # Include & lt; Vector & gt; using namespace std; Int main () {Vector & lt; Pair & lt; Int, int & gt; & Gt; B; B.push_back (make_pair (5,10)); B.push_back (make_pair (75,100)); B.push_back (make_pair (33,67)); B.push_back (make_pair (9, 21)); B.push_back (make_pair (28.667)); Int m = b.size (); Sort (B.Bigin (), B.End ()); Int j = 0; For (Int i = 1; ii ++) {if (b [i]. First & lt; = b [ja] .second) {if (b [i] .second & gt; B [j] .second) {b [ja] .second = b [i] .second; }} And {j ++; B [j] = b [ii]; }} I = J + 1; {Cout & lt; for int i = 0; i & lt; m; i ++) & Lt; B [i]. First & lt; & Lt; "" & Lt; & Lt; B [i] .second & lt; & Lt; Endl; } // Apply binary search now; } I hope this will solve your problem. I left the binary search section as exercise for you.
Comments
Post a Comment