In the last mission, MDCS has successfully shipped N AI robots to Mars. Before they start exploring, system initialization is required so they are arranged in a line. Every robot can be described with three numbers: position (x_i), radius of sight (r_i) and IQ (q_i).
Since they are intelligent robots, some of them will talk if they see each other. Radius of sight is inclusive, so robot can see other all robots in range [x_i - r_i, x_i + r_i]. But they don't walk to talk with anybody, but only with robots who have similar IQ. By similar IQ we mean that their absolute difference isn't more than K.
Help us and calculate how many pairs of robots are going to talk with each other, so we can timely update their software and avoid any potential quarrel.
Input
The first line contains two integers, numbers N (1 ≤ N ≤ 10^5) and K (0 ≤ K ≤ 20).
Next N lines contain three numbers each x_i, r_i, q_i (0 ≤ x_i,r_i,q_i ≤ 10^9) — position, radius of sight and IQ of every robot respectively.
Output
Output contains only one number — solution to the problem.
Example
Input
3 2
3 6 1
7 3 10
10 5 8
Output
1
Note
The first robot can see the second, but not vice versa. The first robot can't even see the third. The second and the third robot can see each other and their IQs don't differ more than 2 so only one conversation will happen.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to count pairs (i,j) such that they see each other (i.e., each robot's sight range includes the other's position). Condition: They see each other if |x_i - x_j| ≤ min(r_i, r_j)?? Wait careful: Each robot can see all robots in its own range. So "they talk if they see each other" meaning both see the other? The problem statement: "some of them will talk if they see each other." Typically that implies mutual visibility: i sees j and j sees i. Then additional condition: |q_i - q_j| ≤ K.
Thus we need count pairs (i<j) such that |x_i - x_j| ≤ r_i and |x_i - x_j| ≤ r_j, and |q_i - q_j| ≤ K.
Equivalently, |x_i - x_j| ≤ min(r_i, r_j). Also |q_i - q_j| ≤ K.
Now N up to 1e5, K up to 20 (small). x_i, r_i, q_i up to 1e9.
We need efficient counting.
This problem looks like from Codeforces? Possibly named "Robots" or something. The constraints: K ≤ 20 is small, suggests grouping by IQ or something.
Observation: Since K is small (≤20), the condition |q_i - q_j| ≤ K means that q_j is within [q_i - K, q_i + K]. For each robot, we need to consider robots with IQ in that range. However, the positional condition is also tricky.
We need to count pairs (i,j) such that they are within each other's radius. That's symmetric: it requires that both distances are within respective radii. Equivalent to: For unordered pair, the distance is less than or equal to both radii. That's same as: |x_i - x_j| ≤ r_i and |x_i - x_j| ≤ r_j. So it's not symmetric in radii, but the condition is symmetric: both constraints must hold.
Alternative: If we think of the condition as: i can see j if x_j in [x_i - r_i, x_i + r_i]. Then both must see each other: x_i in [x_j - r_j, x_j + r_j] and x_j in [x_i - r_i, x_i + r_i]. This is equivalent to: x_i and x_j are within distance min(r_i, r_j) of each other? Let's test: If |x_i - x_j| ≤ r_i and ≤ r_j, then it's exactly that. However, is it possible that |x_i - x_j| ≤ r_i but > r_j? Then j does not see i, so no talk. So indeed we need both. So condition is: |x_i - x_j| ≤ min(r_i, r_j). Good.
Thus problem reduces: count pairs (i<j) with |x_i - x_j| ≤ min(r_i, r_j) and |q_i - q_j| ≤ K.
Now min(r_i, r_j) is not independent. Could consider ordering by r maybe.
Idea: Sort robots by r_i descending? Then for each robot i, consider j < i such that r_j >= r_i? If we sort by r descending, then for i (with r_i) and any j before i, we have r_j >= r_i. Then min(r_i, r_j) = r_i. So condition becomes |x_i - x_j| ≤ r_i and |q_i - q_j| ≤ K. However, note that we must count each pair once. If we sort by r descending and process each i, we consider all previous j (with larger or equal r). But pairs where both have equal r will be counted exactly once if we only consider j before i? They would be counted when processing the later one. However, careful: Suppose both have same r, sorted arbitrarily. Then when processing the later (with same r), condition uses min(r_i, r_j) = r_i (which equals r_j). So condition becomes |x_i - x_j| ≤ r_i. So that's correct. Also we need to ensure we consider pairs where r_i > r_j? But if we sort descending, when processing i, previous j have r_j >= r_i, so if r_i is smaller than r_j, min = r_i, condition uses i's r. So it's okay. But what about pairs where r_i > r_j? Then if we process i after j (since r_i > r_j, i would come before j in descending order? Actually if r_i > r_j, then i would appear before j (since descending). Then when processing j later, j has smaller r, previous includes i (with larger r), min = r_j, condition uses r_j. So we would count it when processing the smaller r robot. So indeed every pair is counted exactly once when we process the robot with the smaller radius (or the later one in case of equal). So this approach works: Sort by r descending; for each robot i (in that order), we need to count among already processed robots (with radius >= r_i) those j such that |x_i - x_j| ≤ r_i and |q_i - q_j| ≤ K.
Now this is like for each i, we have a query: count points (x_j, q_j) with x_j in [x_i - r_i, x_i + r_i] and q_j in [q_i - K, q_i + K], among points inserted so far. Since K is small (≤20), we can handle q range by grouping by q? But q up to 1e9, so not small. However K is small, so for each i we can consider for each possible q' that satisfies |q_i - q'| ≤ K, we need to count points with that exact q' and x in range. But number of distinct q values may be many (up to N). But K is small, so we can maintain a data structure keyed by q, each containing a Fenwick tree or order statistic tree over x coordinates? But N is 1e5, and we need to support queries: given a q value, count number of points with that q in a given x-range. But we also need to insert points as we go. Since we need to answer many queries each involving possibly multiple q values (2K+1 at most 41), we could maintain for each distinct q a balanced BST (like a Fenwick tree if we compress x) but we have many q's. However total inserts are N, and each query would need to query 2K+1 q's, each query on its corresponding Fenwick tree. If we compress x globally, we could have a Fenwick tree per q. But that might be heavy: up to N distinct q, each Fenwick tree of size N would be O(N^2) memory. Not feasible.
Alternative: Since K is small, we can process groups of robots with similar IQ? Possibly we can process all q values, but we can use offline technique? Another approach: Use a BIT over x, but with condition on q. Since q difference ≤ K is small, we could sort by q as well? Possibly we can treat (q, x) as two dimensions. We need to count points with q in [q_i - K, q_i + K] and x in [x_i - r_i, x_i + r_i] among those with radius >= current (i.e., already processed). This is a 2D orthogonal range counting query, with N up to 1e5, K small. But the q dimension range width is small (41) if we consider q_i's. However q values are large; but the condition is about absolute difference. Could compress q values? Because the range is [q_i-K, q_i+K], which can be arbitrary values. But we could map each robot's q to some integer after sorting, then queries become range of up to 2K+1 ids? Not exactly because the q dimension is continuous but we only have discrete points. If we compress q values, then for a given q_i, the q values that satisfy |q_i - q_j| ≤ K are those with compressed index in some range(s) but the q values are not dense; we could precompute for each q_i which q_j's are within K difference? That would be N * N if naive. However since K is small, number of distinct q values within a small numeric range is limited? Not necessarily: q values up to 1e9, but N is 1e5, so there could be many distinct q values. However, for a given q_i, the range [q_i-K, q_i+K] may contain many distinct q values that appear in the dataset. In worst case, if all q_i are distinct but spaced more than K apart, each range contains only one (the robot itself) maybe. But still we cannot iterate over all possible q values within that range because there could be many? Actually if q_i are all distinct and spaced >K apart, then each [q_i-K, q_i+K] contains only q_i itself. But that's fine: we can just query for that exact q value. The worst-case number of distinct q values within a range of width 2K+1 (which is ≤41) is at most the number of robots with q in that interval, but since q values are arbitrary, it's possible that many robots have q in that small interval, because q values can repeat and many robots can have same q. Actually q_i can be any integer up to 1e9, but multiple robots can have same q. The maximum number of distinct q values in an interval of length 41 is at most 42 (if they are integer and all distinct). However, since q_i are integers? Input says numbers, presumably integers, yes. So interval length is 2K+1 ≤ 41. So the maximum number of distinct integer q's in that interval is 41 (if K=20, interval length 41 inclusive of endpoints? Actually from q_i - K to q_i + K inclusive gives 2K+1 values, exactly 41 possible integer q values. So for any i, the set of possible q values that satisfy the condition is a set of at most 41 distinct integer values. However, we need to count points with those q values. So we can maintain for each q (exact integer value) a data structure over x for points with that q. Since there could be many distinct q values overall (up to N), but each query only touches at most 41 of them. So we can have a map from q to a Fenwick tree over compressed x (or a balanced BST). Total memory: sum over distinct q of size of that q's Fenwick tree. Each robot contributes to exactly one q's Fenwick tree. So total size across all q is O(N). For each q, we need to support point updates (add position) and range queries (count positions in [L,R]). That can be done with a Fenwick tree if we compress positions globally but we need separate Fenwick for each q? We could compress positions per q? Actually we can compress x coordinates globally, but each Fenwick tree for a specific q would have to be of size equal to number of distinct x positions overall? That would be too large if we allocate full size for each q. Instead we can use a Fenwick tree that is built on the indices of x after sorting globally? But then each q's Fenwick tree would need to handle updates for all points, but each q only has points at some positions. We could use a BIT with dynamic size: we can store for each q a sorted list of x positions of robots with that q (all robots, not just processed). Then we can use a Fenwick tree over that list's indices, and we need to support point updates (activate a robot when processed) and prefix sum queries. Since we process robots in order of descending r, the set of activated robots for a given q is a subset of all robots with that q. So we can pre-collect all positions for each q. For each q, we sort the positions, then build a Fenwick tree (size = number of robots with that q) initially all zeros. As we process robots (insert them), we update the Fenwick tree at the index corresponding to that robot's position (by adding 1). Then for a query for a given q, we need count of activated robots with positions in [L,R]. We can binary search in the sorted list to get the range of indices [l_idx, r_idx] (first position >= L, last <= R) and then query BIT prefix sum. This gives O(log M) per query per q, where M is count of robots with that q.
Since each robot is inserted once, total updates O(N log N) across all q. Each query (for a robot i) involves up to (2K+1) q values: we need to consider q' = q_i + d for d in [-K, K] that exist? Actually we can simply for each integer q' from q_i - K to q_i + K, if that q' exists in our map, we query that BIT for range count. But there might be many q' that don't appear; we can skip. So each query does at most 41 BIT range queries, each O(log M). Since N=1e5, 41*1e5 = 4.1e6, times log (avg per q maybe log N) ~ 20, total ~80M, which is okay in C++ but Python might be borderline but possible with optimizations? But we need to implement in Python (likely). 4.1e6 * log(1e5) ~ 4.1e6 * 17 = ~70M operations, each a few Python operations, might be borderline but possibly okay if optimized (using list for BIT, binary search, etc). However we also have to sort positions per q and build BITs. Complexity O(N log N) overall.
But careful: We need to process robots in descending r order. However, we also need to consider only robots with r >= current r_i (i.e., already processed). Since we process in that order, we insert each robot after processing its query? Typically we count pairs where j is already inserted and i is current. So we do query first, then insert. Since we want i with smaller radius to count pairs with larger radius, we sort descending by r. For each i (starting from largest r to smallest), we query among already inserted robots (which have r >= current r? Actually if there are ties, the later one will have equal r, and condition uses min(r_i, r_j)=r_i (since r_i equals r_j). In our order, if we sort descending, for equal r, the order is arbitrary; but we need to ensure we count each pair exactly once. If we process in order and for each i we query only previously inserted robots, then for two equal r robots, whichever comes later will count the pair. That's fine. But note: Condition for both equal r: we need |x_i - x_j| ≤ r_i (which equals r_j). In the later processed robot i, it will query earlier j (which also has equal r), and the condition uses r_i. So it's correct because we use r_i in query. So fine.
Thus algorithm:
Read N, K.
robots = list of tuples (r, x, q, index?) Actually we need to sort by r descending. So store (r_i, x_i, q_i). Also we'll need to group by q for precomputation. So we'll collect all robots with same q.
Preprocessing:
Build a dict: q_to_positions = {} mapping integer q to list of x positions of all robots. Actually we also need to know which robot corresponds to which index in that list for updates. So we can assign each robot an ID. For each robot, store its q, x, r.
After reading all robots, for each q, create a sorted list of x positions of all robots with that q. Also we'll need a BIT for each q (Fenwick tree of zeros initially). Since we will be activating robots as we process them, we need a way to find the index of a robot in its q's sorted x list. So we can precompute for each robot its index in its q list. We'll store that index along with robot data.
Implementation steps:
Create list robots: each as dict or tuple: (r, x, q, idx_in_qlist). We'll compute idx_in_qlist after building q_to_positions and sorting.
Steps:
Parse input.
For each robot i (0..N-1), store x, r, q.
Build dict: q_to_xlist = defaultdict(list). For each robot, append (x, i) maybe? But we need sorted x list, so just append x.
After building, for each q, sort q_to_xlist[q]. Also create a dict mapping from (q, x) to index? But multiple robots could have same q and same x? Possibly yes. Since x can be same. In that case, we need to differentiate them. The BIT will store counts per position; if multiple robots share same q and x, they will be at the same x coordinate. In the sorted list, duplicates are allowed. For BIT, we can treat each robot as a separate point; but they share the same x coordinate. The usual approach: for each q, we have sorted list of unique x? But then we need to handle multiple points at same x. We can either compress to unique x and use a BIT that counts multiple points at same x (i.e., increment by count). But then updates are increments of 1 per robot, and we need to map each robot to the index of its x in the unique sorted list. However, if there are duplicates, multiple robots map to same index; we need to update the BIT at that index accordingly. That's fine: each robot triggers an update at that index (add 1). Query counts the sum over indices whose x in [L,R]. That correctly counts all robots at those positions.
So we should create per q a sorted list of unique x values? But we also need to map each robot to the index of its x among unique x. That works: for each q, create sorted list of unique x from robots with that q. Then for each robot, we find its x in that list (via binary search or precomputed mapping). Since N is 1e5, we can do for each robot: after building unique sorted list, we use binary search to find index, but that would be O(N log M) overhead, which is fine. Alternatively, we can precompute a dict per q mapping x to index.
Simplify: For each q, let xs = sorted(set of x among robots with that q). Then create BIT of length len(xs). For each robot with that q, we compute idx = bisect_left(xs, x). Since xs is sorted and contains that x, we can store idx.
But careful: If there are duplicates, all robots with same q and same x get the same idx. That's fine.
Now, processing order:
Sort robots by r descending (largest first). For ties, any order is fine. We'll have list sorted_robots = sorted(robots, key=lambda t: -t[0]) (or t.r). Actually each robot: we have (r, x, q, idx_in_qlist). Also we might need original index? Not needed.
Initialize answer = 0.
Process each robot in sorted_robots:
Let r_i, x_i, q_i, pos_idx (index in BIT for its q) but we don't need that for query; we need to query other q's.
For each d from -K to K:
q_target = q_i + d
if q_target in q_to_bit: (we have a BIT for that q)
code
xs_list = q_to_xs[q_target] (sorted unique x's for that q)
# need to count activated robots with x in [x_i - r_i, x_i + r_i] and q = q_target.
L = x_i - r_i
R = x_i + r_i
# find left index: idx_l = lower_bound(xs_list, L)
# find right index: idx_r = upper_bound(xs_list, R) - 1
if idx_l <= idx_r:
count = bit_query(q_target, idx_r) - bit_query(q_target, idx_l - 1) (with 1-indexed BIT)
answer += count
After query, we need to insert current robot into its own q's BIT: update at its idx (pos_idx) by +1.
But caution: When we query for q_target = q_i, we might count robots with same q (including possibly itself?) But we are only counting among already inserted robots. Since current robot is not inserted yet (we query before insertion), we won't count itself. So fine.
Edge: if d=0 (same q) we count other robots with same q and similar IQ? Actually condition requires |q_i - q_j| ≤ K, so d=0 is included. So we query all q in [q_i-K, q_i+K] inclusive.
Now, does this count all pairs exactly once? As argued, we process in descending r, and query only previously inserted robots (with r >= current). But note: condition uses min(r_i, r_j). For a pair (i,j) with r_i < r_j, when processing i (the smaller), j is already inserted (since j has larger r and processed earlier). The query for i uses its own r_i as bound (since min = r_i). So condition is |x_i - x_j| ≤ r_i. But we also need condition |x_i - x_j| ≤ r_j. Since r_j >= r_i, the first condition implies second? Not necessarily: if r_i < r_j, we need both distances ≤ r_i and ≤ r_j. If |x_i - x_j| ≤ r_i, then automatically ≤ r_j because r_j >= r_i. So yes, the condition reduces to |x_i - x_j| ≤ r_i. So it's enough. For pair with equal r, we process later one (say i after j). Then condition for i is |x_i - x_j| ≤ r_i. That's min(r_i, r_j)=r_i, so same. Also note: when we query, we use r_i bound, which is correct. So algorithm works.
But need to be careful: The condition we derived earlier is exactly |x_i - x_j| ≤ min(r_i, r_j). If we process smaller r first? Wait we process descending r, so each robot i when processed has the smallest r among processed? Actually descending order means we start with largest r. So when we process a robot i, all previously inserted robots have r >= r_i (since they were larger or equal). So i is the one with the smallest r so far (or equal). So pairs where i is the smaller-r robot get counted at that moment (since the larger-r robot is already inserted). Pairs where i is the larger-r robot will not be counted later because when we process the smaller robot later, that will count the pair. So each unordered pair is counted exactly once (when the smaller-r robot is processed). Good.
One more nuance: What if two robots have same r, but we process one then the other. The first robot (when processed) does not have the other inserted, so pair not counted then. When second is processed (with same r), the first is inserted (since earlier) and condition uses second's r (which equals both). So pair counted exactly once. Good.
Thus answer is sum of counts.
Now complexity: Preprocessing: building dict grouping by q: O(N). Sorting each q's x list: total O(N log N) across all q (since sum of sizes = N). Sorting the robots by r: O(N log N). For processing: For each robot, we iterate over up to (2K+1) q_target values. For each q_target that exists, we do two binary searches on its xs_list (O(log M)) and two BIT prefix queries (or one range query via two prefix queries) O(log M). So total O(N * (2K+1) * log N). With N=1e5, K=20 -> 41*1e5 = 4.1e6, each log factor ~ 17, ~70M operations. In Python, might be okay with efficient coding (bisect from built-in, BIT as list of ints). However, we need to be careful to avoid overhead from dictionary lookups for each q_target. Also we need to check if q_target exists in the dict; we can do q_target in q_to_bit (dictionary) and then retrieve bit and xs list. But we also need BIT for each q. We can store for each q a tuple (xs_list, BIT). The BIT can be a list of ints (Fenwick). The BIT operations: update(idx, delta) and query(idx) (prefix sum). We'll implement 1-indexed BIT inside the list of length size+1.
We also need to map each robot to its index in its q's BIT. We'll precompute idx for each robot: use bisect on the unique x list to get 1-indexed index (since BIT uses 1-indexed). We can store idx (0-indexed or 1-indexed). We'll use 1-indexed for BIT: position = bisect_left(xs_unique, x) + 1 (since xs_unique is sorted, and we know x exists). Actually if we store unique xs, we need to ensure that for each robot we find the correct index. Since xs_unique contains that x, bisect_left returns the index in 0-based. Then for BIT we need index+1.
Alternatively, we could store for each q a dict mapping x to list of indices? But simple.
Now we also need to handle the fact that each robot will be inserted after query. So BIT for each q starts empty; we update when we process.
Potential pitfalls: K can be 0, so only same q. Works.
Sort by r descending: robot1 (r=6), robot3 (r=5), robot2 (r=3).
Processing robot1 (r=6,x=3,q=1): query q_target from -2..2 around 1 -> q values: -1,0,1,2,3. Only q=1 exists (maybe others? no). So query q=1's BIT (empty) -> count 0. Insert robot1 into q=1 BIT.
Processing robot3 (r=5,x=10,q=8): query around 8: q values from 6 to 10. q=8,10 exist? q=8 (robot3 itself, not inserted yet) q=10 exists (robot2 not inserted yet? robot2 hasn't been inserted because its r is 3 and we are at robot3, so robot2 not inserted). Also q=6,7,9 maybe not exist. So count 0. Insert robot3 into q=8 BIT.
Processing robot2 (r=3,x=7,q=10): query around 10: q values 8,9,10,11,12. q=8 exists (robot3 inserted), q=10 exists (robot2 itself not inserted). So query q=8: L = 7-3=4, R=7+3=10. In q=8's xs list (only x=10), is 10 in [4,10]? Yes. So count=1. Query q=10: (no inserted yet) count=0. So total answer=1. Works.
Thus algorithm is correct.
Now we must ensure we only count each pair once, and we've accounted that.
Now consider possible issue: When two robots have same q and same x? Works fine, because BIT counts multiple.
Now complexity: N=1e5, each robot query up to 41 q values. But what if many q values exist? At worst, many of these q_target values might not exist; we can check quickly via dict. That's cheap. So actual number of BIT queries per robot equals number of distinct q in [q_i-K, q_i+K] that appear in the dataset, which is at most 41 but could be less. So up to 41.
BIT operations: For each existing q_target, we perform two binary searches and two BIT prefix sums (or one range query using two prefix sums). That's O(log M). So total operations ~ 2 * (number of q_target) * log M.
Now potential memory: For each distinct q, we store xs list (unique x values) of size equal to number of distinct x for that q. Sum over q of distinct x could be up to N if all x distinct per q. And for each q we store BIT array of length = number of distinct x + 1. So total memory O(N). That's fine.
Implementation details:
We'll use Python's standard libraries: sys.stdin.read for fast input.
Data structures:
robots: list of tuples (r, x, q)
also need later to map each robot to its q and x and index in BIT.
Better: After grouping by q, we can construct per q a sorted list of unique x.
Then we need to assign each robot a bit_idx. Since we have list of robots, we can for each robot compute idx by using bisect on its q's xs list. We'll store that idx in a separate list or as part of robot tuple.
But we also need to sort robots by r descending. So we can create an array of objects or tuples: (r, x, q, bit_idx). Or we can store (r, x, q, q_group, bit_idx) but we can compute bit_idx after building groups.
Procedure:
Read N, K.
Initialize list robots_raw = [] with (x, r, q) but we can store as (x, r, q).
For each, append (x, r, q).
Build dict: q_to_xlist = defaultdict(list). For each robot, q_to_xlist[q].append(x).
For each q, create sorted unique list: xs = sorted(set(q_to_xlist[q])). Store in dict q_to_xs.
Also create BIT for each q: q_to_bit = {}; for each q, BIT = [0] * (len(xs) + 1). Also maybe store both xs and BIT in a structure, e.g., q_to_data = {q: (xs, BIT)}.
Now, for each robot, we need to compute its index in its q's BIT. We have its x and q. Use xs = q_to_xs[q]; idx = bisect_left(xs, x) (0-based). Since x is guaranteed to be in xs (as we built from set containing it), idx is correct. Then we want 1-indexed for BIT: bit_idx = idx + 1.
We'll store robot data in a list: each as (r, x, q, bit_idx). However we also need to know its q to access BIT for insertion and query. So we keep q.
But note: when processing, for query we need to access other q's BIT and xs. So we have q_to_data for that.
So let's create list robots_proc = [].
For each (x, r, q) in robots_raw:
xs = q_to_xs[q]
idx = bisect_left(xs, x)
bit_idx = idx + 1
robots_proc.append((r, x, q, bit_idx))
Sort robots_proc by r descending (largest first). If multiple same r, any order.
But careful: We need stable ordering? Not required.
Initialize answer = 0.
Process each robot in sorted order:
r_i, x_i, q_i, bit_idx_i = robot
L = x_i - r_i
R = x_i + r_i
code
For d in range(-K, K+1):
q_target = q_i + d
if q_target in q_to_data:
xs_target, bit_target = q_to_data[q_target]
# find left and right indices in xs_target
# left_idx = first index where xs_target[idx] >= L
l = bisect_left(xs_target, L)
if l == len(xs_target): continue # no elements
r_idx = bisect_right(xs_target, R) - 1 # last index <= R
if l > r_idx: continue
# BIT queries are 1-indexed
# Convert to 1-indexed: l1 = l + 1, r1 = r_idx + 1
cnt = query(bit_target, r_idx+1) - query(bit_target, l)
answer += cnt
# after queries, insert current robot: update its q's BIT at bit_idx_i by 1.
_, bit_self = q_to_data[q_i] # we could store bit separately
update(bit_self, bit_idx_i, 1)
Now we must consider integer overflow? answer can be up to N*(N-1)/2 ~ 5e9, fits in 64-bit, Python int fine.
Potential performance improvements:
Use local variables for functions to reduce attribute lookups.
Pre-store q_to_data as list or dict; dict lookup per q_target is okay.
For each robot, we iterate over d from -K to K. K <= 20, so at most 41 iterations. That's fine.
For each q_target that exists, we do two bisect calls. Could precompute for each q the xs list. Use bisect from built-in module.
BIT operations: Each update and two queries per q_target (two queries for range). That's 241N ~ 8.2e6 BIT ops; each BIT op is O(log M) with while loops; total ~ 8.2e6 * logN ~ 140M loop iterations? Actually each BIT operation loops about log2(size) ~ up to 17 iterations. So total steps maybe 8.2e6*17 ~ 140M. This might be high but possibly still okay in PyPy if optimized. But we can try to reduce number of BIT queries: For each q_target we perform two BIT prefix sums. That's 2 per q_target. Since 41 q_targets, that's 82 BIT prefix sums per robot. That's a lot: 82 * 1e5 = 8.2e6 BIT prefix sum calls, each about log steps (say 17) = 139.4M loop iterations. Plus updates: N updates each log steps -> 1.7M. Plus bisects: 41 per robot * log size (maybe 17) -> 70M comparisons. So total operations maybe ~200M. Might be borderline but possibly passes with PyPy if code is optimized.
But we can further optimize: For each q_target, we could perform a single Fenwick tree query by using range query function? That still two prefix sums. However we can perhaps combine by using a Fenwick tree that supports range sum with two prefix sums anyway. So no reduction.
We might reduce the number of q_target queries by only considering q_target that actually have some robots (dictionary check). But that's already minimal.
Another approach: Because K is small, we could process by grouping robots with similar IQ? Possibly use a sliding window on IQ after sorting by something? But this BIT approach seems straightforward.
Maybe we can reduce overhead by using offline approach: sort robots by x and use sweeping? But condition includes radii. However, the min(r_i, r_j) condition after sorting by r is easier.
Alternative: Instead of per-q BITs, we could use a global data structure with offline queries? For each robot i, we need to count among previous robots (with r >= r_i) those with q in [q_i-K, q_i+K] and x in [x_i - r_i, x_i + r_i]. This is a 2D range query (x, q) with q range small width. Since K <= 20, we could for each robot treat each possible q offset as separate "q group"? But still q values are arbitrary integers.
Another possible optimization: Instead of having separate BIT per q, we could compress the q dimension as well using a segment tree over q, each node storing a BIT over x? That would be heavy.
Given constraints, the per-q BIT approach seems plausible. However, we need to handle memory and time. Let's estimate more precisely: Each BIT operation involves a while loop with bit operations. For 8.2e6 operations each with average loop length log2(avg size per q). The average number of robots per q is N / distinct_q. Distinct_q could be up to N, so many q's have only 1 robot. For those, BIT size 1, log=0? Actually BIT of size 1 (array length 2? Actually if only 1 distinct x, BIT length = 2, query/update loop runs only 1 iteration (since idx changes). So average log maybe small. But worst-case if many robots share the same q, then BIT size could be large. But then number of q_target queries for that q is many. However total BIT operations is sum over all queries of log(size). Could be high but maybe okay.
We can also implement BIT as list of ints, and we can use local variables and inline loops.
But there is also the overhead of Python function calls for each query. We can avoid function overhead by defining update and query as inner functions or as methods? Or we can inline code inside the loop? That would be messy but possible.
Better: Write simple functions and use them. Since the number of calls is large, function call overhead may be significant. But we can perhaps store references to the functions locally.
Alternatively, we could use a Fenwick tree implemented as a class with methods; but that adds overhead.
We could store BIT as list and define update and query as local nested functions to capture 'bit'? Actually we need to pass bit list each time. We'll just have plain functions.
I think it's okay for 1e5 with K=20. Many solutions in C++ exist; Python might pass with optimization and using PyPy.
But we need to ensure we use fast I/O and avoid unnecessary overhead. Also we can precompute for each robot the range [L,R] and maybe store.
Potential bug: In the condition, r_i can be up to 1e9, L = x_i - r_i may be negative; x_i, r_i are non-negative, but L could be negative. That's fine; the binary search on xs list works: bisect_left on negative L will return 0 if all xs are non-negative, which is correct because we want x >= L, and xs are >=0. So fine.
Now we must also consider the case where r_i is large so that interval covers all robots; then left bound may be negative huge? But x_i and r_i are up to 1e9, so L could be as low as -1e9, R as high as 2e9. That's fine.
Now we need to check: Are we counting pairs where i and j have exactly the same r? Our process: when processing robot with smaller r (or later if equal), we count pairs where j (earlier) has r_j >= r_i. For equal r, one is processed earlier; when the later processes, it uses its own r_i (which equals r_j) and counts if |x_i - x_j| ≤ r_i. So correct.
Now test on simple cases:
Case 1: N=2, K=0, both q same, positions x1=0,x2=1, r1=1,r2=1. They see each other? |x1-x2|=1 ≤ min(1,1)=1, yes. So answer 1. Our process: Sort by r descending (both equal, order arbitrary). Suppose order: robot1 first, robot2 second. Process robot1: query q_target = q (only), BIT empty -> 0; insert robot1. Process robot2: query q_target = q, L=1-1=0, R=1+1=2. BIT for q contains robot1 at x=0, which is in range -> count 1. Insert robot2. Answer=1.
Case 2: Asymmetric radii: r1=5, r2=2, x1=0, x2=3, K=0, q same. Condition: |x1-x2|=3 ≤ min(5,2)=2? 3>2, so they do not see each other. Our process: Sort descending r: robot1 (r=5) first, robot2 (r=2) second. Process robot1: query -> 0, insert. Process robot2: L=3-2=1, R=3+2=5, BIT contains robot1 at x=0, 0 not in [1,5]? Actually 0 is not >=1, so count 0. So answer 0. Good.
Now consider scenario where r_i is large and covers many points, but we only consider those with radius >= current. That's fine.
Now consider potential double counting: Could a pair be counted twice? Only if we count both when processing i and j. But we only count when processing the later one (smaller r). Since we query only previously inserted, and we insert after query, each pair is counted exactly once.
Now confirm that we are not missing pairs where r_i = r_j but both have same r and we process both? Only later counts.
Now confirm that the condition with min(r_i, r_j) and using r_i for later robot works because r_i = min(r_i, r_j). So yes.
Thus algorithm stands.
Now we need to think about memory: storing q_to_data: for each q, we have xs list (list of ints) and BIT list (list of ints). Total memory O(N). But for q with many robots, BIT size = number of unique x for that q. However if there are duplicates, we have fewer entries. But worst-case all robots have distinct q, then we have N entries each with xs list length 1, BIT length 2. That's fine.
Implementation details in Python:
We'll read input using sys.stdin.buffer.read().split() for speed.
Pseudo:
import sys, bisect
from collections import defaultdict
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
N = int(next(it))
K = int(next(it))
robots_raw = []
q_to_xs_all = defaultdict(list) # list of x (with duplicates) for grouping
for _ in range(N):
x = int(next(it))
r = int(next(it))
q = int(next(it))
robots_raw.append((x, r, q))
q_to_xs_all[q].append(x)
code
# Build per q unique sorted xs and empty BIT.
q_to_data = {}
for q, xs_list in q_to_xs_all.items():
# unique sorted
uniq_xs = sorted(set(xs_list))
# BIT initialized with zeros, length = len(uniq_xs)+1
bit = [0] * (len(uniq_xs) + 1)
q_to_data[q] = (uniq_xs, bit)
# Prepare list of robots with their index in BIT.
robots = []
for x, r, q in robots_raw:
xs, _ = q_to_data[q]
idx = bisect.bisect_left(xs, x) # 0-based
bit_idx = idx + 1
robots.append((r, x, q, bit_idx))
# Sort by r descending
robots.sort(key=lambda t: -t[0])
# BIT functions (inline for speed maybe)
def bit_update(bit, i, delta):
while i < len(bit):
bit[i] += delta
i += i & -i
def bit_query(bit, i):
s = 0
while i > 0:
s += bit[i]
i -= i & -i
return s
ans = 0
# Process
for r_i, x_i, q_i, bit_idx_i in robots:
L = x_i - r_i
R = x_i + r_i
# iterate over possible q targets
for d in range(-K, K+1):
q_target = q_i + d
data_target = q_to_data.get(q_target)
if data_target is None:
continue
xs_target, bit_target = data_target
# binary search for range in xs_target
# left index
l = bisect.bisect_left(xs_target, L)
if l == len(xs_target):
continue
r_idx = bisect.bisect_right(xs_target, R) - 1
if l > r_idx:
continue
# range sum query on BIT: sum from l+1 to r_idx+1 inclusive
# use bit_query(bit_target, r_idx+1) - bit_query(bit_target, l)
cnt = bit_query(bit_target, r_idx+1) - bit_query(bit_target, l)
ans += cnt
# insert current robot
_, bit_self = q_to_data[q_i]
bit_update(bit_self, bit_idx_i, 1)
print(ans)
if name == 'main':
main()
Check for off-by-one: For l = bisect_left(xs_target, L). That returns first index with xs_target[idx] >= L. So if there are xs_target exactly equal to L, it's included. For right: bisect_right(xs_target, R) returns first index > R. So r_idx = that -1 is last index <= R. Good. Then BIT indices: left1 = l+1, left1-1 = l. So range sum = query(r_idx+1) - query(l). That's correct.
Potential issue: When l = 0, query(l) is query(0) which returns 0 as per function.
Now we must consider that we may double count pairs when the robot's own q_target includes its own q, but since it is not inserted yet, it's fine. However, what about when there are multiple robots with same x and q? In BIT, we have counts per unique x? We use unique x list. For duplicates, multiple robots map to same index; each robot insertion increments BIT at that index. So query returns total count. Good.
But caution: When we binary search on xs_target (unique x), we find indices of unique x values. If there are multiple robots with same x, they are all represented by that index. So when we query BIT, we get the count of all inserted robots with that x. That's correct.
Now verify with an example with duplicate x and q: two robots at same position x=5, q=10, r1=0, r2=0? Actually r=0, they see each other if distance 0 <= min(0,0)=0 so yes. They have same q and x. Process descending r: both r=0, order arbitrary. First robot: query q_target 10: L=5-0=5,R=5+0=5 -> xs_target for q=10 includes x=5 at some index. BIT empty -> count 0. Insert. Second robot: query same: now BIT has one robot at x=5, which is in range, count=1. So answer 1. Works.
Now consider robots with same q but different x. Works.
Now edge case: L may be > R? But L = x_i - r_i could be > R? Only if r_i negative? r_i >=0, so L <= x_i <= R, so L <= R always. So okay.
Now complexity wise, need to ensure we use Python's bisect module which is fast.
Potential performance improvements:
Precompute for each q_target the xs_target and bit_target, and also maybe store them in a list for quick access. But we only get from dictionary each time.
Use local variable references inside loop: assign q_to_data_get = q_to_data.get etc.
For the d loop, we can compute q_min = q_i - K, q_max = q_i + K, and iterate over d in range(q_min, q_max+1). But it's the same.
Since K <= 20, the loop is small.
Potential memory: storing robots_raw and robots list with same data might double memory but N=1e5, fine.
Alternative: We could avoid storing robots_raw separate: while reading, we can accumulate (x, r, q) in a list, then later build per q xs list using that list. Then we need to compute bit_idx for each robot after building xs. So we need to store robot data anyway.
One nuance: When we build q_to_xs_all, we used a list of x (including duplicates). That's fine.
But we then built unique sorted list per q. However, when computing idx for each robot, we used bisect_left on the unique list. For duplicates, multiple robots with same q and x will get the same idx, which is fine.
Now what about robots with the same q and x but different r? They will map to same idx, and BIT will store count of inserted ones. Works.
Now we must ensure that when we process robots in descending r order, the BIT insertion order matters only for counting. That's fine.
Now test with random small data to verify.
But there might be an oversight: The condition |x_i - x_j| ≤ min(r_i, r_j) is equivalent to both robots seeing each other. Our method uses that when processing robot with smaller r, we check |x_i - x_j| ≤ r_i (since min = r_i). But does this fully capture the condition that j sees i? Since j has larger radius, if |x_i - x_j| ≤ r_i, then automatically ≤ r_j. So yes.
But wait: Is it possible that the condition "i sees j" means that j is within i's range, and "j sees i" means i is within j's range. This is symmetric, so the condition is both distances ≤ respective radii. For pair (i,j) with r_i < r_j, the condition is: |x_i - x_j| ≤ r_i AND |x_i - x_j| ≤ r_j. The second is redundant if first holds because r_j >= r_i. So it's equivalent to |x_i - x_j| ≤ r_i. So indeed we only need to check with the smaller radius. So our method is correct.
Now we must consider the case where r_i = r_j. Then condition is |x_i - x_j| ≤ r_i. Our method uses the later robot's r (which equals both). So correct.
Now what about if we sort descending and process, the robot with smaller r is processed later. So for each pair, the later robot (with smaller or equal r) checks the condition. So each pair counted exactly once.
Now check for potential double counting with equal r but same robot? Not.
Thus solution is correct.
Now we need to ensure we treat large N, K up to 20. Complexity as described.
Potential improvements: Use Fenwick tree with only as many elements as the number of positions per q. Already done.
Now we can consider if there is a more efficient approach: Use a sweep line on x with segment tree over q? But K small so per-q BIT is simpler.
Now consider whether we need to handle negative x? Input says x_i >= 0, but after subtraction it could become negative; that's fine.
Now let's think about possible pitfalls with integer overflow in Python? No.
Edge case: N=1 => answer 0.
Now test with provided example: already did.
Now let's test with some custom cases.
Case: N=2, K=10, (x=0, r=0, q=0), (x=0, r=0, q=10). Since |q diff| = 10 ≤ K? If K=10, then yes. Condition: |x_i - x_j| = 0 ≤ min(0,0)=0 => they see each other. So answer 1. Our process: q1=0, q2=10. K=10 so for robot1, q_target includes 0..10. For robot1 processing (r=0? Actually both r=0, order arbitrary). Suppose robot1 first (r=0, q=0). query q_target from -10..10: q=0 exists (BIT empty), q=10 maybe not yet inserted. count 0. Insert robot1. Then robot2 (r=0, q=10): query q_target from 0..20: q=10 exists (BIT empty? robot1 is q=0, not q=10) and q=0 exists? q=0 exists, and robot1 has q=0. Check range L=R=0. BIT for q=0 has robot1 at x=0, which is within range, so count 1. Insert robot2. answer=1. Good.
Now case where r_i is huge but q difference > K: not counted.
Now test with many robots same q and random positions, large K. It should count all pairs that satisfy distance ≤ min(r_i, r_j). Our method sorts by r and uses BIT per q. That's like counting for each robot i the number of earlier robots j with same q (or within K) and x in [x_i - r_i, x_i + r_i]. But what about q difference within K but not same q? That's handled by iterating over d.
Now we need to ensure we correctly count pairs where q_i != q_j but within K. For those, we query q_target = q_j (where q_j = q_i + d). So we count them.
Now is there any risk of counting pairs twice across d? No, because each q_target is distinct, and each j has exactly one q_j, so it will be counted exactly once when d = q_j - q_i. Since we query all d in [-K, K], we will include that q_j exactly once. However, if there are multiple q_j that are within K but not exactly q_i + d? Actually all q_j within [q_i-K, q_i+K] are covered by some d. So each j is counted at most once (provided we don't also count it when d=0 for same q? But same q is covered by d=0. So each j appears in exactly one q_target (its own q). So no double counting.
Thus algorithm is correct.
Now we should consider memory and performance.
Potential improvement: Instead of using bisect for each query, we could precompute for each robot the range indices in each q's xs list? But that would be too much because each robot would need for each q_target (up to 41) the left and right indices. That's 41*N indices storage, maybe 4e6 integers, which is okay but not necessary. But we could compute on the fly.
Now we need to be careful about Python recursion? Not used.
Now we should test with maximum N and K to estimate runtime. I'll do mental estimate: 1e5 robots, each query up to 41 q_target, each with two bisects (log average maybe ~10) and two BIT prefix sums (log average maybe ~10). So total operations: 1e5 * 41 * (2log + 2log) maybe 4*log per q_target. Actually two bisects each O(log M) and two BIT queries each O(log M) = 4 * log M per q_target. With 41 q_target => 164 * log M per robot. For 1e5 robots => 1.64e7 * log M. log M average maybe 5-10? So 8e7-1.6e8 operations. That's quite high. But many q_target may not exist, so we skip quickly with dict lookup. For many robots, the number of q_target that exist might be small, because q values are spread out? Not necessarily; worst-case all robots have q within a small range such that for each robot, all 41 q_target values exist. For example, all q_i are between 0 and 40, then for each robot, the range [q_i-20, q_i+20] may include all q values from 0 to 40, so all 41 possible q_target exist. So worst-case number of q_target that exist could be 41 for every robot. So we must handle that.
Thus worst-case number of BIT operations = N * 41 * 2 = 8.2e6 BIT prefix queries (each prefix query includes log steps) + N * 41 * 2 = 8.2e6 BIT updates? No, update is only once per robot, not per query. So total BIT operations: ~8.2e6 * 2 (since each range query uses two prefix queries) = 16.4e6 prefix queries? Wait: For each q_target we do one range query which is two prefix queries. So that's 2 * (number of q_target queries) prefix BIT queries. Number of q_target queries = N * (avg number of q_target that exist). In worst-case 41, that's 4.1e6 q_target queries (since N=1e5, 41*1e5 = 4.1e6). Each such query requires two BIT prefix sums, so 8.2e6 BIT prefix sum calls. Each BIT prefix sum call is O(log M) operations. So total BIT steps maybe 8.2e6 * average log M. Also we have N updates, each O(log M). So total BIT steps ~ 8.2e6 * log M + 1e5 * log M.
Now log M average: For a given q, M is number of unique x positions for that q. In worst-case, if all robots have the same q, then M = N (unique x maybe N). Then for each robot, the number of q_target that exist might be 1? Actually if all have same q, then for each robot, only d=0 exists (since other q_targets not present). So the worst-case for BIT size (M large) corresponds to fewer q_target queries per robot. Conversely, if many q_target exist, they likely have smaller per-q counts because the robots are distributed among many q values. So product (number of queries per robot) * (log of size per q) might be balanced.
Let's try to bound worst-case total complexity more carefully.
Suppose we have D distinct q values. For each robot i, the number of q_target that exist is at most 2K+1 but limited to the number of distinct q values in that interval. In worst-case, if all robots' q values are within a range of width 2K, then D could be up to 2K+1 (since q are integers, but they could be many distinct values within that range, but width is at most 41, so the maximum number of distinct integer q values within any interval of length 2K is 2K+1. So D cannot exceed 2K+1? Actually D is total distinct q values over all robots. They could be scattered, but if we want many q_target to exist for each robot, the robots must have many distinct q values within the small interval. However, the total number of distinct q values could be large, but for a given robot, its query interval is only 41 wide, so the maximum number of distinct q values that can appear in that interval is at most 41. So worst-case each robot can have up to 41 distinct q_targets.
Now consider distribution: If there are many distinct q values, but they are spaced out, then for a given robot, many of the 41 possible q values may not have any robots, so less queries.
Thus worst-case queries per robot is 41. So we accept that.
Now per query BIT cost: For each q_target, we do two BIT prefix sum queries. The BIT for that q_target has size equal to number of unique x among robots with that q. Let's denote for each q, n_q = number of robots with that q. Then the total number of BIT prefix sum operations contributed by queries is: For each robot i, for each q in [q_i-K, q_i+K] that exists, we do two prefix sums on BIT for that q. So overall, we can think of each pair (i, q) where q is a q value that appears and within K of q_i, we incur two BIT queries. The total number of such (i, q) pairs is sum over robots i of (# of q values within K that exist). This is at most N * (2K+1) = 4.1e6. So total BIT prefix queries = 2 * that = 8.2e6.
Now each BIT query on q's BIT costs O(log U_q), where U_q is number of unique x positions for that q (which is ≤ n_q). So total BIT query complexity is O( sum over (i,q) of log U_q ). This sum can be bounded? We can think of each robot contributes to queries on BITs of nearby q's. Since each robot's own q is one of these, the total sum over all q of (number of robots that query this q) * log U_q. The number of queries to a particular q is equal to the number of robots i such that q is within K of q_i. That is essentially number of robots with q_i in [q-K, q+K]. This is similar to the total number of pairs (i, q) where q is fixed and i's q_i within K. This can be large if many robots have q within K of a given q. In worst-case, if all robots have q in a small interval of width 2K, then for any q, all robots are within K? Actually if all robots have q in [0,20], K=20, then for q=10, all robots have q_i in [0,20] which is within K? |q_i - 10| ≤ 20? Yes, because max difference 10? Actually if interval width is 20, the maximum distance from 10 to any endpoint is 10, which is ≤20. So all robots would be within K of q=10. So the number of queries to q=10 could be N. Similarly for each q in that interval, many robots might query it. But note that each robot i queries only q values that actually exist. If all robots have q in a set of size 41, then each robot i will query all 41 q values (since its own q_i is in that set, the interval will cover all 41 values). So each q value will be queried by all N robots. So total number of query operations to a particular q's BIT is N. And for that q, n_q is about N/41? Actually if all robots are uniformly distributed among 41 q values, then n_q ≈ N/41. So for that q, each BIT query costs O(log (N/41)) ≈ O(log N). So total BIT query cost per q is N * O(log N). Summed over 41 q's gives 41 * N * log N ≈ 4.1e6 * 17 ≈ 70 million steps. Plus the same number for prefix sums? Actually each query to a q involves two BIT prefix sums, but still O(log n_q). So total BIT steps maybe ~140 million. That's high but maybe acceptable in PyPy if optimized.
But we also have bisect operations: For each (i,q) we do two binary searches on the xs list of that q. That's O(log U_q) each. So that's similar cost. So total operations maybe 2-3 times that, maybe 300-400 million operations. That might be too slow in Python.
We need to think of optimizations.
Observation: The bisect and BIT operations both are O(log U_q). Could we combine them? Possibly we can use a Fenwick tree that also can do range queries by indices we compute. That's separate.
But maybe we can avoid per-query binary searches by using a global coordinate compression and using a 2D BIT? However K is small but q dimension is small as well.
Alternative approach: Since K is small (≤20), we can group robots by q. But perhaps we can use an offline sweep on x, using a sliding window of q? Another idea: sort robots by x, and use a segment tree over q?
def query(bit, idx):
res = 0
while idx > 0:
res += bit[idx]
idx -= idx & -idx
return res
Note: In query for range [l, r] (1-indexed), we do query(r) - query(l-1).
In code above: l (0-indexed) -> left 1-indexed = l+1. r_idx (0-indexed) -> right 1-indexed = r_idx+1. So we need query(bit, r_idx+1) - query(bit, l). Because l corresponds to l+1-1 = l. Actually careful: query(bit, l) gives sum up to index l (1-indexed). But our l is 0-indexed; we want sum from left 1-indexed = l+1. So to get sum from left inclusive, we need query(right) - query(left-1). left-1 = (l+1)-1 = l. So we can compute as:
left1 = l + 1
right1 = r_idx + 1
cnt = query(bit, right1) - query(bit, left1 - 1) = query(bit, right1) - query(bit, l)
Yes, because left1 - 1 = l. So we can do as above: cnt = query(bit, r_idx+1) - query(bit, l)
Works if l == 0? query(bit, 0) returns 0 as while loop won't run; we need to ensure query(bit, 0) returns 0. In our function, while idx>0, so query(bit,0) returns 0. Good.