Interval Selection


Problem Statement :


Given a set of n intervals, find the size of its largest possible subset of intervals such that no three intervals in the subset share a common point.

Input Format

The first line contains an integer, s, denoting the number of interval sets you must find answers for. The s.(n+1) subsequent lines describe each of the s interval sets as follows:

1.The first line contains an integer, n, denoting the number of intervals in the list.
Each line i of the n subsequent lines contains two space-separated integers describing the respective starting (ai) and ending (bi) boundaries of an interval.
Constraints
1 <= s <= 100
2 <= n <= 1000
1 <=  ai <= bi <= 10^9
Output Format

For each of the s interval sets, print an integer denoting the size of the largest possible subset of intervals in the given set such that no three points in the subset overlap.



Solution :



title-img


                            Solution in C :

In C++ :





#include <algorithm>
#include <cstdio>
using namespace std;

pair<int,int> a[1002];

int main() {
int i,m,n,x,y,z,may;


	for (scanf("%d",&z);z;--z) {
		scanf("%d",&n);
		for (i=1;i<=n;++i) {
			scanf("%d%d",&a[i].second,&a[i].first);
		}
		sort(a+1,a+n+1);
		a[x=y=m=0]=make_pair(-1,-1);
		for (i=1;i<=n;++i) {
			may=-1;
			if (a[x].first<a[i].second) {
				may=x;
			}
			if ((y>may) && (a[y].first<a[i].second)) {
				may=y;
			}
			if (may==x) {
				x=i;
				++m;
			}
			else if (may==y) {
				y=i;
				++m;
			}
		}
		printf("%d\n",m);
	}
	return 0;
}








In Java :





import java.util.*;
import java.io.*;
import static java.lang.Math.*;

public class Solution {
	static class Foo53 {
		void main() {
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(System.in));
				int T = Integer.parseInt(br.readLine().trim());
				for (int i = 0; i < T; i++) {
					int N = Integer.parseInt(br.readLine().trim());
					int[][] arr = new int[N][2];
					for (int j = 0; j < N; j++) {
						String[] s = br.readLine().trim().split("\\s+");
						arr[j][0] = Integer.parseInt(s[0].trim());
						arr[j][1] = Integer.parseInt(s[1].trim());
					}
					int res = foo(arr);
					System.out.println(res);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (br != null) {
					try { br.close(); } catch (Exception e) { e.printStackTrace(); }
				}
			}
		}
		
		Deque<Integer> deque;
		int foo(int[][] arr) {
			int res = 0;
			int n = arr.length;
			deque = new LinkedList<Integer>();
			Arrays.sort(arr, new Comparator<int[]>() {
				public int compare(int[] a, int[] b) {
					return a[0] - b[0];
				}
			});
			for (int[] a : arr) {
				int left = a[0], right = a[1];
				while (!deque.isEmpty() && deque.getFirst() < left)
					deque.removeFirst();
				if (deque.size() < 2) {
					res++;
					add(right);
				} else {
					if (deque.getLast() > right) {
						deque.removeLast();
						add(right);
					}
				}
			}
			return res;
		}
		void add(int val) {
			if (!deque.isEmpty() && deque.getLast() > val) {
				deque.addFirst(val);
			} else {
				deque.addLast(val);
			}
		}
	}
	
	public static void main(String[] args) {
		Foo53 foo = new Foo53();
		foo.main();
	}
}








In C :






#include <stdio.h>
#include <stdlib.h>

long long v,zas[1100],d[3000][3],ii,jj,kk,s[10000][2];
long long aa[1100],a[1100][1100],i,j,k,l,m,n,t,tt;


int com(const void*x, const void *y)
{
long long *xx,*yy;

xx = (long long *)x;
yy = (long long *)y; 

if(xx[0]>yy[0]) return 1;
if(xx[0]==yy[0] && xx[2]==1) return 1; 
  
return -1;
}

int main()
{

scanf("%lld",&t);
for(tt=0;tt<t;tt++)
 {
 scanf("%lld",&n);
 for(i=0;i<n;i++) scanf("%lld %lld", &s[i][0], &s[i][1]);


// s[0][0] = -5; 
// s[0][1] = -1;
  
 
// for(i=0;i<n;i++)
//  for(j=0;j<n;j++) a[i][j] =0;

  
 for(i=0;i<n;i++) 
    {
     d[2*i][0]=s[i][0];
     d[2*i][1]=i;
     d[2*i][2]=0;
     
     d[2*i+1][0]=s[i][1];
     d[2*i+1][1]=i;
     d[2*i+1][2]=1; 
    }
 
 qsort(d,n*2,sizeof(d[0]),com);

l=0;
m=0;
v=0;

for(i=0;i<2*n;i++)
  {
   ii = d[i][1];
  
   if(d[i][2]==0)
     {
    for(j=0;j<l;j++) 
       {
       a[ii][zas[j]] = a[zas[j]][ii] = aa[zas[j]]+1;
       if(a[ii][zas[j]]>v) v = a[ii][zas[j]];
       }
    
     zas[l] = ii;
     l++;
     aa[ii] = m+1;   
     if(aa[ii]>v) v = aa[ii];
     }
   else
     {
     if(aa[ii]>m) m=aa[ii];	
     
     j=0;
     while(zas[j]!=ii) j++;
     l--;
     zas[j] = zas[l];
     
     for(j=0;j<l;j++) 
        if(a[ii][zas[j]] > aa[zas[j]]) 
                 aa[zas[j]] = a[ii][zas[j]];
     }  
  }


printf("%lld\n",v);

//for(i=0;i<2*n;i++) printf("%lld %lld %lld\n",d[i][0],d[i][1],d[i][2]);

}


return 0;
}








In Python3 :





t = int(input())
for _ in range(t):
  n = int(input())
  I = []
  for _ in range(n):
    a, b = list(map(int, input().split()))
    I.append((a, b))
  I.sort(key = lambda x: (x[1], x[0]))
  temp = -1
  lasta = 0
  lastb = 0
  res = 0
  for a, b in I:
    if a>lastb:
      res+=1
      lasta = a
      lastb = b
    elif a>temp:
      res+=1
      temp = lastb
      lasta = a
      lastb = b
  print(res)
                        








View More Similar Problems

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →