Mr. X and His Shots
Problem Statement :
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of Mr. X and the range of M players. Si represents the strength of each player i.e. the number of shots player can stop. Your task is to find: Game Rules: A player can stop the ith shot if the range overlaps with the player's fielding range. Input Format The first line consists of two space separated integers, N and M. Each of the next N lines contains two space separated integers. The ith line contains Ai and Bi. Each of the next M lines contains two integers. The ith line contains integers Ci and Di. Output Format You need to print the sum of the strengths of all the players. Constraints: 1 <= N, M <= 10^5 1 <= Ai, Bi, Ci , Di <= 10^8
Solution :
Solution in C :
In C++ :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std ;
struct segment
{
bool isleft ;
int point ;
bool isfielder ;
} ;
vector < segment > v ( 400010 ) ;
vector < segment > :: iterator it ;
bool cmpr ( segment & a , segment & b )
{
if ( a.point != b.point )
{
return a.point < b.point ;
}
if ( a.isleft != b.isleft )
{
return a.isleft ;
}
return ! ( a.isfielder ) ;
}
int main ()
{
int n , m ;
cin >> n >> m ;
int counter = 0 ;
for ( int i = 0 ; i < n ; i ++ )
{
int a , b;
cin >> a >> b ;
segment temp ;
temp.isleft = true ;
temp.point = a ;
temp.isfielder = false ;
v [ counter ++ ] = temp ;
temp.isleft = false ;
temp.point = b ;
v [ counter ++ ] = temp ;
}
for ( int i = 0 ; i < m ; i ++ )
{
int a , b;
cin >> a >> b ;
segment temp ;
temp.isleft = true ;
temp.point = a ;
temp.isfielder = true ;
v [ counter ++ ] = temp ;
temp.isleft = false ;
temp.point = b ;
v [ counter ++ ] = temp ;
}
it = v.begin () ;
advance ( it , counter ) ;
sort ( v.begin () , it , cmpr ) ; // segment intersection problem
int bat = 0 , field = 0 ;
long long int ans = 0 ;
for ( int i = 0 ; i < counter ; i ++ )
{
if ( v [ i ].isleft == true )
{
if ( v [ i ].isfielder )
{
ans += bat ; // intersects with all the batsman
field ++ ;
}
else
{
ans += field ;
bat ++ ;
}
}
else
{
if ( v [ i ].isfielder )
{
field -- ;
}
else
{
bat -- ;
}
}
}
cout << ans ;
return 0 ;
}
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static int binarySearch(long[] arr, long num) {
int head = 0, tail = arr.length - 1;
while (head <= tail) {
int mid = (head + tail) / 2;
if (arr[mid] <= num) {
head = mid + 1;
} else {
tail = mid - 1;
}
}
return head;
}
public static long strenth(long[] heads, long[] tails, long C, long D) {
long result = heads.length;
result -= (heads.length - Solution.binarySearch(heads, D));
result -= (tails.length - Solution.binarySearch(tails, -C));
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), M = sc.nextInt();
long[] A = new long[N], B = new long[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextLong(); B[i] = -sc.nextLong();
}
Arrays.sort(A); Arrays.sort(B);
long sum = 0L;
for (int i = 0; i < M; i++) {
sum += Solution.strenth(A, B, sc.nextLong(), sc.nextLong());
}
System.out.println(sum);
}
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define _DEBUG_ 0
typedef struct sRange {
int s;
int e;
} Range;
int cmpfunc(const void *a, const void *b) {
Range *this = (Range *)a;
Range *that = (Range *)b;
if (this->s > that->s) return 1;
if (this->s < that->s) return -1;
return this->e - that->e;
}
__inline__ int overLaps(Range *a, Range *b) {
if ((a->s <= b->e) && (a->e >= b->s)) return 1;
return 0;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N = 0, M = 0, A = 0, B = 0, C = 0, D = 0, i = 0, j = 0;
int S = 0;
scanf("%d %d", &N, &M);
Range *shots = (Range *)malloc(N * sizeof(Range));
Range *field = (Range *)malloc(M * sizeof(Range));
for (i = 0; i < N; i++) {
scanf("%d %d", &A, &B);
shots[i].s = A;
shots[i].e = B;
}
qsort(shots, N, sizeof(Range), cmpfunc);
#if 0 //_DEBUG_
for (i = 0; i < N; i++) {
printf("%d %d\n", shots[i].s, shots[i].e);
}
#endif
// get fielders
for (i = 0; i < M; i++) {
scanf("%d %d", &C, &D);
field[i].s = C;
field[i].e = D;
}
qsort(field, M, sizeof(Range), cmpfunc);
// Keep moving fielder and shot together
i = 0;
j = 0;
while (i < M && j < N) {
if (field[i].e < shots[j].s) i++; // increment fielder
else if (field[i].s > shots[j].e) j++; //increment shot
else {
// they are overlapping, check all the shots
int tempJ = j;
while (tempJ < N && shots[tempJ].s <= field[i].e) {
if (overLaps(&shots[tempJ], &field[i])) {
S++;
}
tempJ++;
}
i++;
}
#if _DEBUG_
printf("s %d, f %d, S %d\n", j, i, S);
#endif
}
printf("%d\n", S);
return 0;
}
In Python3 :
import sys
import os
# STEP 1: Take in parameters:
firstLine = input().split()
N = int(firstLine[0])
M = int(firstLine[1])
maxVal = 1000000
tally1 = [0] * maxVal
tally2 = [0] * maxVal
# STEP 2: Take in the ranges of the shots:
for i in range(0,N):
line = input().split()
tally1[int(line[0])] += 1
tally2[int(line[1]) + 1] -= 1
# STEP 3: Tally the strengths of the players:
for i in range(1,maxVal):
tally1[i] += tally1[i-1]
tally2[i] += tally2[i-1]
sumStrengths = 0
for j in range(0,M):
player = input().split()
playerStart = int(player[0])
playerEnd = int(player[1])
sumStrengths += tally1[playerEnd] + tally2[playerStart]
print(sumStrengths)
View More Similar Problems
Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →Maximum Element
You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each
View Solution →Balanced Brackets
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra
View Solution →