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

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →