We are given N frogs on the X-axis at positions A1,...,AN. Two frogs can communicate directly if the distance between them ≤ K. Communication can be indirect via other frogs (transitive closure). So essentially we have a graph where vertices are frogs, edges between i and j if |Ai - Aj| ≤ K. Then queries: for given pairs (A, B), answer if they are in same connected component.
N, P up to 10^5. Coordinates up to 1e9, K up to 1e9.
We need to compute connected components efficiently. Straightforward approach: sort frogs by coordinate, then for sorted list, we can connect consecutive frogs if difference ≤ K? Wait: The graph is not just nearest neighbors. However, the condition for edges is based on distance. For points on a line, the connectivity via such an adjacency (within distance K) defines components that are exactly intervals where any two points within the component are connected if the gap between consecutive sorted points is ≤ K? Actually, if we sort positions, then if there is a gap > K, that separates components because any two points across that gap would have distance > K? Let's analyze.
Given sorted coordinates x1 ≤ x2 ≤ ... ≤ xN. Define edges between i and j if |xi - xj| ≤ K. This is like an unweighted graph on points where edges exist between any two points within distance K. This graph's connectivity can be determined by considering only edges between consecutive sorted points? Actually, it's known that two points are in the same connected component if and only if there is a chain of points such that each consecutive pair has distance ≤ K. This is equivalent to the condition that for any two points in the same component, the maximum gap between sorted points within that component is ≤ K? Wait: If we have sorted points, consider building a graph where we connect i to i+1 if xi+1 - xi ≤ K. Then it's easy to see that if we have a path from i to j using only such edges (neighbors), then the condition holds because each step is ≤ K, so they can communicate. However, is it possible that two points are connected via longer jumps but the consecutive gaps may be > K? For example: points at positions 0, 10, 20 with K=15. The gaps: 10 and 10, both ≤ 15, so consecutive edges exist, so it's connected. That's fine. But suppose points at 0, 16, 30 with K=15. Gaps: 16 >15, so no edge between 0 and 16, and between 16 and 30 gap=14 ≤15, so there is edge between 16 and 30. Are 0 and 30 connected? 0-30 distance =30 >15, direct not allowed. Could there be a path: 0 -> 16? no, because 0-16=16>15. 0 -> 30? no. So not connected. So component splits at gaps >K. So indeed, connectivity in this graph is determined by connecting consecutive points if their gap ≤ K. The components are maximal contiguous segments in the sorted order where the gaps between consecutive points are ≤ K. This is because the graph is essentially an interval graph? Let's prove:
Take sorted points. Define an undirected graph G with vertices as points, edges between any two points with distance ≤ K. The graph G is what's known as a unit interval graph (if K fixed). Actually it's a "threshold graph" where intervals are [xi-K, xi+K]. Intersection graph of intervals of length 2K centered at points. Connectivity in such intersection graphs corresponds to intervals overlapping if the union of intervals is connected? But simpler: sort points. If we consider the "neighbor graph" connecting consecutive points when difference ≤ K, then clearly that graph is a subgraph of G, and its connectivity components are subsets of those of G. Conversely, if two points are in the same component of G, there is a path in G. Suppose we have two points xi < xj. There exists a sequence of points xi = p0, p1, ..., pm = xj such that each consecutive pair distance ≤ K. By sorting all points in the path, we can show that the maximum gap between consecutive sorted points among the set of all points in the component cannot exceed K (otherwise there would be a jump > K between some consecutive sorted points in that component, but does that necessarily break connectivity? Let's think: Suppose we have points in sorted order within the component: a1 < a2 < ... < ak. If there is a gap > K between ai and ai+1, then any point to the left of ai+1 has distance to any point to the right of ai at least ai+1 - ai > K, so there is no edge crossing that gap. However, could there be a chain that goes from left side to right side without directly using the gap? The chain would have to go through some intermediate point(s) that lie between ai and ai+1. But there are none because they are consecutive in the sorted component. So no point can cross the gap. Thus left and right sides are disconnected. So indeed, connectivity components correspond to intervals where consecutive gaps ≤ K. So we can compute components by sorting frogs by coordinate, then scanning: assign component ID to each frog based on grouping when gap > K.
But careful: "More than 1 frog can be on the same point" — that means coordinates can be equal. The gap would be 0, which is ≤ K, so they are in same component.
Thus we can sort the frogs by coordinate, then assign component IDs. However, we also need to answer queries with frog indices (original numbering 1..N). So we need to map each frog index to its component ID. Then answer queries: if comp[A] == comp[B] -> Yes else No.
Complexities: O(N log N) for sorting, O(P) for queries.
Now implement:
Read N, K, P.
Read array A of size N (1-indexed). We'll create a list of (coord, index). Sort by coord. Then traverse sorted list: comp_id = 0 initially. For first frog: assign comp[ index ] = comp_id. For each subsequent frog: if coord - prev_coord <= K, then assign same comp_id; else increment comp_id and assign. At the end we have comp array for each index.
Then for each query, read a,b (1-indexed). Check if comp[a] == comp[b] => print "Yes" else "No".
Edge cases: K could be 0. Then only frogs at same coordinate can communicate (directly). Our method: gap <= 0 means only exactly equal. Since if coordinates are equal, difference =0 <=0, they are grouped; otherwise gap >0 >0 => new component. That's correct.
N and P up to 1e5, coordinates up to 1e9, fits in int but better use long (maybe 64-bit). In Java, use long for differences? Actually int up to 1e9, K up to 1e9, difference may be up to 1e9 as well, but within 2e9? Actually coordinates can be 0..1e9, so max diff <= 1e9, fits in int (2e9). But we should be safe with long.
Now confirm with example: N=5, K=3, A=[0,3,8,5,12]. Sorted: (0,1), (3,2), (5,4), (8,3), (12,5). Differences: 3-0=3 <=3 -> same; 5-3=2<=3 -> same; 8-5=3<=3 -> same; 12-8=4>3 -> new component. So comp: idx1=0, idx2=0, idx4=0, idx3=0? Actually 8 is index3, comp same as previous? Since 8-5=3<=3, so same component. So idx3 also comp0; idx5 comp1. So component0: frogs 1,2,3,4; component1: frog5. Queries: (1,2): both comp0 -> Yes; (1,3): both comp0 -> Yes; (2,5): comp0 vs comp1 -> No. Works.
Thus solution is simple.
But is there any nuance? The graph defined by distance ≤ K is not necessarily exactly the same as grouping by consecutive gaps? We argued yes, but need to be careful: The condition for direct communication is if distance ≤ K. Indirect communication means there is a sequence such that each consecutive pair distance ≤ K. In the sorted order, if all consecutive gaps ≤ K, then the set is clearly connected (since you can go from leftmost to rightmost stepping through consecutive points). Conversely, if there is a gap > K between two consecutive points (in sorted order of the whole set), then points left of the gap cannot reach points right of the gap, because any path would have to cross that gap at some step, which would require a pair of points with distance > K? More formally: Let sorted positions x1 ≤ x2 ≤ ... ≤ xN. Suppose there exists i such that x_{i+1} - x_i > K. Then consider set L = {x1,...,xi} and R = {x_{i+1},...,xN}. For any a in L and b in R, distance >= x_{i+1} - xi > K, so direct edge absent. Moreover, any path from a to b would contain some edge between a node in L and a node in R. But all such edges have distance > K, so impossible. Hence no connectivity. Therefore the connected components are exactly maximal intervals where consecutive gaps ≤ K. So correct.
Thus problem solved.
Now just need to implement in Java.
We'll create a class Frog with coordinate and index.
Sort using Arrays.sort with Comparator.
Traverse and assign component IDs.
Read queries and output.
Potential pitfalls: Input size large, use BufferedReader.
Implementation:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
int[] coords = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
coords[i] = Integer.parseInt(st.nextToken());
}
Frog[] frogs = new Frog[N];
for (int i = 0; i < N; i++) {
frogs[i] = new Frog(coords[i], i);
}
Arrays.sort(frogs, Comparator.comparingInt(f -> f.coord));
int[] comp = new int[N];
int compId = 0;
comp[frogs[0].idx] = compId;
for (int i = 1; i < N; i++) {
if (frogs[i].coord - frogs[i-1].coord <= K) {
// same component
comp[frogs[i].idx] = compId;
} else {
compId++;
comp[frogs[i].idx] = compId;
}
}
for (int i = 0; i < P; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
if (comp[a] == comp[b]) {
out.println("Yes");
} else {
out.println("No");
}
}
out.flush();
}
static class Frog {
int coord;
int idx;
Frog(int coord, int idx) {
this.coord = coord;
this.idx = idx;
}
}
}
Check: We use zero-indexing internally.
That's it.
But note: Input constraints include P up to 1e5, so we use PrintWriter for output.
Time complexity: O(N log N + P). Memory: O(N).
Potential issues: Using Comparator.comparingInt might be okay; but ensure no overflow when subtracting, but int fine.
Edge case: N=1. Then only one frog, compId stays 0, queries comparing that frog with itself: Yes if same? Query could be 1 1, then comp[0]==comp[0] => Yes. Good.
Now we can present the solution.
But there is one subtlety: The problem says "More than 1 frog can be on the same point on the X-axis." That's covered.
Thus final answer.
Let's double-check with a test: N=4, K=5, coords: [0,10,5,20]. Sorted: (0,1), (5,3), (10,2), (20,4). Gaps: 5-0=5<=5 -> same; 10-5=5<=5 -> same; 20-10=10>5 -> new. So comp: idx1=0, idx3=0, idx2=0, idx4=1. Queries: (1,4): No; (1,2): Yes; (2,4): No; (3,4): No. Let's verify connectivity: Positions: 0,5,10,20; K=5. Frogs at 0,5,10 are pairwise within 5? 0-5=5 yes; 5-10=5 yes; 0-10=10>5, but via 5 they can communicate (0-5 and 5-10). So they are connected. 20 is isolated because distance to 10=10>5. So correct.
Thus solution stands.
Now I'll produce final answer with explanation.
In problem statement, "speak to each other" means direct or indirect communication as typical.
Potential alternative misinterpretation: "send a message" might require that each step only uses direct communication? That's what we assume.
Thus answer is correct.
Now produce final output.
```java
import java.io.;
import java.util.;
public class Main {
static class Frog {
int coord, idx;
Frog(int coord, int idx) {
this.coord = coord;
this.idx = idx;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// read first line
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
// read coordinates
int[] coords = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
coords[i] = Integer.parseInt(st.nextToken());
}
// create and sort frogs by coordinate
Frog[] frogs = new Frog[N];
for (int i = 0; i < N; i++) {
frogs[i] = new Frog(coords[i], i);
}
Arrays.sort(frogs, Comparator.comparingInt(f -> f.coord));
// assign component ids
int[] comp = new int[N];
int compId = 0;
comp[frogs[0].idx] = compId;
for (int i = 1; i < N; i++) {
if (frogs[i].coord - frogs[i-1].coord <= K) {
comp[frogs[i].idx] = compId;
} else {
compId++;
comp[frogs[i].idx] = compId;
}
}
// answer queries
for (int i = 0; i < P; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()) - 1; // to 0‑index
int b = Integer.parseInt(st.nextToken()) - 1;
out.println(comp[a] == comp[b] ? "Yes" : "No");
}
out.flush();
}
}