One King Solution

Revision en1, by jarvisnaharoy, 2019-06-13 08:52:22

PROBLEM LINK:

ONEKING

DIFFICULTY:

EASY-MEDIUM

PROBLEM:

Given N (≤100000) intervals [Ai, Bi], one such interval can be deleted by placing a bomb at x if Ai ≤ x ≤ Bi. Find minimum number of bombs required to delete all intervals.

EXPLANATION:

In this problem we can minimize the number of bombs by dropping the bombs at intersection points. So we have to divide the intervals into disjoint sets such that each set consists of intervals having a common intersection point.

Example: (1,5) , (4,5) , (2,3) , (3,4) , (4,4) , (6,8)

We can divide the following intervals into {(1,5) , (5,5)} {(2,3) , (3,4) , (4,4)} {(6,8)}

For each set 1 bomb is required i.e Number of such sets = Number of minimum bombs

How can we find a set of intervals having a common intersection point?

  1. Arrange the intervals according to the increasing oreder of lower bounds of intervals.

  2. Let the sequence be : (a1,b1) , (a2,b2) , (a3,b3) , (a4,b4) , . . . , (an,bn)

  3. We will check if (a1,b1) , (a2,b2) intersects.

    if a2<b1 then (a1,b1) and (a2,b2) intersects and intersection interval will be = (a2,min(b1,b2))

    lets say (x,y) = (a2,min(b1,b2))

  4. Now consider (a3,b3).It will intersect (a1,b1) and (a2,b2) if and only if (a3,b3) intersects (x,y) i.e if (a3,b3) intersects the intersection interval of (a1,b1) and (a2,b2).

    Again if a3<y then (x,y) and (a3,b3) intersects and we will modify (x,y) as

    (x,y)=(a3,min(b3,y))
  5. We will continue until we find (x,y) has no intersection with interval (ai,bi). So the set {(a1,b1),(a2,b2),...,(ai-1,bi-1)} has a common intersection point and interval (x,y) is common to all the intervals in the set. We can place a bomb at any point in (x,y) to destroy all the intervals in the set.

  6. Continue the procedure now starting with (ai,bi).

Pseudo code:

n = number of intervals
pairs = array of intervals

n,pairs=input

sort(pairs,pairs+n)

count=1 //minimum number of bombs = 1
test_pair=pairs[0]

for j = 1 to n:
    if pairs[j].lower_bound <= test_pair.upper_bound :
	test_pair.lower_bound = pairs[j].lower_bound
	test_pair.upper_bound = min(pairs[j].upper_bound,test_pair.upper_bound)
    
    else:
	count++
	test_pair = pairs[j]

print count

Complexity: O(N).

SOLUTIONS:

https://pastebin.com/q9ZikK1k

Tags #codechef, #oneking

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English jarvisnaharoy 2019-06-13 19:39:16 4 Tiny change: 'ity: **O(N).**\n\n#' -> 'ity: **O(NlogN).**\n\n#'
en3 English jarvisnaharoy 2019-06-13 15:30:51 2 Tiny change: '{(1,5) , (5,5)} \n{(' -> '{(1,5) , (4,5)} \n{('
en2 English jarvisnaharoy 2019-06-13 14:47:33 443 (published)
en1 English jarvisnaharoy 2019-06-13 08:52:22 2529 Initial revision (saved to drafts)