Starfleet


Problem Statement :


In a galaxy far away, there is a constant battle between the republic and the droid army. The droid army decided to launch their final attack on the republic. They have N space-fighters.

Initially the ith fighter is located at (xi, yi). All of the space-fighters move with constant velocity V units/sec in the positive X direction. i.e., fighter at (xi, yi) moves to (xi+V, yi) in 1 second. The ith space-fighter broadcasts enemy information at a frequency fi.

The republic is not scared of the artificially intelligent droid force as they have Yoda. Yoda has a special power, at any time T he can choose a region of the droid army and block one specific frequency F. This power has one constraint; it can be applied only in the form of a two sided unbounded axis parallel rectangular box open towards the both the directions across X axis (refer image below for clarity). If a frequency (F) is blocked all the space-fighters in the region having the frequency F can’t communicate.



Given the initial positions of the space-fighters, and their velocity, you are to answer queries of the following form:

YU YD T

where YU, YD are the bounds on y-axis inside which YODA can block a frequency at time T. In the region described by the query, after a time T seconds from the start, if Yoda can chose one frequency (F) he wishes to, what is the maximum number of communications he can block?

Input Format

Each test case is described as follows; the first line contains 3 space separated integers N - the number of space-fighters, Q - the number of queries you have to answer, and V - the velocity of the space-fighters separated by a single space.

N lines follow, each containing 3 space separated integers xi, yi, and fi, denoting the x co-ordinate, y co-ordinate and the frequency at which the ith ship broadcasts respectively. Each of the next Q lines contain 3 space separated integers representing YU, YD, T respectively. Refer the figure for more clarity

Note: Points on the boundaries should be counted as well.


Output Format

For each query you are to output a single integer denoting the result.



Constraints


1 <= N <= 50000
1 <= Q <= 30000
1 <= V <= 10000
-109 <= xi <= 109
-109 <= yi <= 109
1 <= fi <= 109
-109 <= YU <= 109
-109 <= YD <= 109
1 <= T <= 10000
YU >= YD



Solution :



title-img


                            Solution in C :

In  C++  :








#include <stdio.h>
#include <algorithm>
#include <map>
#define STEP_SIZE 5000
#define MAXN 50005
using namespace std;

int N, Q, V;
int x[MAXN], y[MAXN], F[MAXN], f[MAXN];
int fN;

map<int, int> freqCompression;

int occur[15][15][50005];
int best[15][15];
pair<int, int> fp[MAXN];

int main()
{
	scanf("%d%d%d", &N, &Q, &V);
	fN=0;
	for(int i=0; i < N; ++i){
		scanf("%d%d%d", x+i, y+i, F+i);
		if(freqCompression[F[i]] == 0)
			freqCompression[F[i]]=++fN;
		F[i]=freqCompression[F[i]]-1;
		fp[i]=make_pair(y[i], F[i]);
	}
	sort(fp, fp+N);
	for(int i=0; i < N; ++i)
		f[i]=fp[i].second;
	for(int i=0; i <= N; i += STEP_SIZE)
		for(int j=i; j <= N; j += STEP_SIZE){
			int I=i/STEP_SIZE, J=j/STEP_SIZE;
			for(int k=0; k < 50000; ++k)
				occur[I][J][k]=0;
			best[I][J]=0;
			for(int k=i; k < j; ++k){
				++occur[I][J][f[k]];
				if(occur[I][J][f[k]] > best[I][J])
					best[I][J]=occur[I][J][f[k]];
			}
		}
	for(int i=0; i < Q; ++i){
		int a, b, t;
		scanf("%d%d%d", &a, &b, &t);
		int c=lower_bound(fp, fp+N, make_pair(b, -1))-fp;
		int d=lower_bound(fp, fp+N, make_pair(a, 999999999))-fp;
		int low=c/STEP_SIZE+1, upp=d/STEP_SIZE;
		int stop=min(low*STEP_SIZE, d);
		int start=max(upp*STEP_SIZE, stop);
		if(upp<low)
			upp=low;
		int B=best[low][upp];
		for(int j=c; j < stop; ++j){
			++occur[low][upp][f[j]];
			if(occur[low][upp][f[j]] > B)
				B=occur[low][upp][f[j]];
		}
		for(int j=start; j < d; ++j){
			++occur[low][upp][f[j]];
			if(occur[low][upp][f[j]] > B)
				B=occur[low][upp][f[j]];
		}
		printf("%d\n", B);
		for(int j=c; j < stop; ++j){
			--occur[low][upp][f[j]];
		}
		for(int j=start; j < d; ++j){
			--occur[low][upp][f[j]];
		}
	}
	return 0;
}








In    Java  :









import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;

public class Solution {

static class Query{
HashMap<Integer,Integer> ShipFrequency;
int Answer;
int Total;
int Singletons;
public Query()
{
ShipFrequency = null;
Answer = 0;
}
public void Answer()
{
System.out.println(Answer);
}
}
static class Task{
Query Q;
boolean begin;
public Task(Query Q,boolean begin)
{
this.Q = Q;
this.begin = begin;
}
public void Do(
HashMap<Integer,Integer> HM,int Total,int Singletons)
{
if(begin)
{
Q.ShipFrequency =
 (HashMap<Integer, Integer>) HM.clone();
Q.Total = Total;
Q.Singletons = Singletons;
}
else
{
int A = 0;
int F = -1;
Iterator<Integer> It = HM.keySet().iterator();
Total -= Q.Total;
while(It.hasNext())
{
int T = It.next();
int Temp = HM.get(T)-(
Q.ShipFrequency.containsKey(T)?Q.ShipFrequency.get(T):0);
Total -= Temp;
A = Math.max(A,Temp);
if(Temp>A)
{
    A = Temp;
    F = T;
}
if(A>=Total)
{
    break;
}
}
if(A==0 && Singletons>Q.Singletons)
{
A = 1;
}
Q.Answer = A;
}
}
}

public static TreeMap<Integer,ArrayList<Integer>> Ships =
 new TreeMap<Integer,ArrayList<Integer>>();
public static int TotSing;

public static void AddToShips(int X,int F)
{
if(Ships.containsKey(X))
{
Ships.get(X).add(F);
}
else
{
ArrayList<Integer> L = new ArrayList<Integer>();
L.add(F);
Ships.put(X,L);
}
}

public static void main(String[] args) {
Scanner In = new Scanner(System.in);
int N = In.nextInt();
int Q = In.nextInt();
In.nextInt();

HashSet<Integer> Singletons = new HashSet<Integer>();
HashSet<Integer> ToRemove = new HashSet<Integer>();
for(int i=0 ; i<N ; i++)
{
In.nextInt();
int X = In.nextInt();
int F = In.nextInt();
AddToShips(X,F);
if(Singletons.contains(F))
{
ToRemove.add(F);
}
else
{
Singletons.add(F);
}
}
Iterator<Integer> it = ToRemove.iterator();
while(it.hasNext())
{ Singletons.remove(it.next()); }
TotSing = Singletons.size();
ArrayList<Query> Queries = new ArrayList<Query>();
TreeMap<Integer,ArrayList<Task>> Tasks 

= new TreeMap<Integer,ArrayList<Task>>();
for(int i=0 ; i<Q ; i++)
{
int U = In.nextInt();
int D = In.nextInt();
In.nextInt();
Query Qu = new Query();
Queries.add(Qu);
if(Tasks.containsKey(D-1))
{
Tasks.get(D-1).add(new Task(Qu,true));
}
else
{
ArrayList<Task> L = new ArrayList<Task>();
L.add(new Task(Qu,true));
Tasks.put(D-1,L);
}
if(Tasks.containsKey(U))
{
Tasks.get(U).add(new Task(Qu,false));
}
else
{
ArrayList<Task> L = new ArrayList<Task>();
L.add(new Task(Qu,false));
Tasks.put(U,L);
}
}
HashMap<Integer,Integer> Freq =
 new HashMap<Integer,Integer>();
int iSingletons = 0;
int Tot = 0;
Iterator<Integer> It = Tasks.keySet().iterator();
Iterator<Integer> It2 = Ships.keySet().iterator();
int LastShip;
LastShip = It2.next();
while(It.hasNext())
{
int TaskPos = It.next();
while(LastShip<=TaskPos)
{
Iterator<Integer> It3 = Ships.get(LastShip).iterator();
Tot += Ships.get(LastShip).size();
while(It3.hasNext())
{
int T = It3.next();
if(Freq.containsKey(T))
{
Freq.put(T,Freq.get(T)+1);
}
else if(Singletons.contains(T))
{
iSingletons++;
}
else
{
Freq.put(T,1);
}
}
Ships.put(LastShip,new ArrayList<Integer>());
if(It2.hasNext())
{
LastShip = It2.next();
}
else
{
break;
}
}
Iterator<Task> It3 = Tasks.get(TaskPos).iterator();
while(It3.hasNext())
{
It3.next().Do(Freq,Tot,iSingletons);
}
}
Iterator<Query> ItQ = Queries.iterator();
while(ItQ.hasNext())
{
ItQ.next().Answer();
}
In.close();
}

}








In   Python3 :






import bisect
from collections import defaultdict

N,Q,_ = map(int,input().split())
a = defaultdict(list)
y = list()
for _ in range( N ):
    _,y_,freq = map(int,input().split())
    a[ freq ].append( y_ )
    y.append( y_ )
    
a = { freq:sorted(y) for freq,y in a.items() if len(y) > 1 }
y = sorted( y )

res = []
for _ in range( Q ):
    y_max, y_min, T = map(int,input().split())
    lres = 0
    index_start = bisect.bisect_left(y, y_min)
    if y[ index_start ] <= y_max:
        lres = 1
        for freq in a:
            index_start = bisect.bisect_left( a[freq], y_min )
            index_stop = bisect.bisect_right( a[freq], y_max )
            lres = max( lres, index_stop - index_start )
    res.append( lres )
print(*res, sep = '\n')
                        








View More Similar Problems

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

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 →