There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).
Write a program that for given current values a_i will find the maximum possible number of boxers in a team.
It is possible that after some change the weight of some boxer is 150001 (but no more).
Input
The first line contains an integer n (1 ≤ n ≤ 150000) — the number of boxers. The next line contains n integers a_1, a_2, ..., a_n, where a_i (1 ≤ a_i ≤ 150000) is the weight of the i-th boxer.
Output
Print a single integer — the maximum possible number of people in a team.
Examples
Input
4
3 2 4 1
Output
4
Input
6
1 1 1 4 4 4
Output
5
Note
In the first example, boxers should not change their weights — you can just make a team out of all of them.
In the second example, one boxer with a weight of 1 can be increased by one (get the weight of 2), one boxer with a weight of 4 can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of 3 and 5, respectively). Thus, you can get a team consisting of boxers with weights of 5, 4, 3, 2, 1.
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 are given n boxers, each with initial weight a_i (1 ≤ a_i ≤ 150000). Each boxer can change his weight by at most 1 (increase by 1, decrease by 1, or stay same), but resulting weight must be positive (≥1) and integer. Also note the note: weight can be up to 150001. We need to select a subset of boxers (we can decide each one's final weight within constraints) such that all final weights in the subset are distinct (unique). And we want to maximize the size of the subset.
Essentially, we need to assign each chosen boxer a final weight w_i ∈ {a_i - 1, a_i, a_i + 1} (subject to w_i ≥ 1) and ensure all w_i are distinct, and maximize the number of boxers we can assign distinct weights. All boxers are initially with given a_i. We can also decide not to include some boxers.
Goal: maximum cardinality of set of boxers with distinct final weights after allowed adjustments.
We can think of this as a matching or assignment problem: we have n boxers, each can choose from up to 3 possible weights (depending on a_i). We need to assign distinct integers (weights) to as many boxers as possible, each assignment must be from the boxer's allowed set.
We need to compute maximum matching size between boxers and weight values (which can be up to maybe 150001+1? Actually note: a_i ≤ 150000, and we can increase by 1 → max possible weight = 150001). But weight also must be positive, so min possible weight = 1. So weight domain from 1 to 150001.
But the number of possible weight values is up to 150001, which is manageable. However n up to 150000. So we need an efficient algorithm.
We can model as a bipartite graph: left side boxers, right side weight values. Each boxer is connected to up to 3 weights (a_i-1, a_i, a_i+1, if valid). We need maximum matching size. Since both sides are up to 150000 and edges about 3n (max 450k), we could use Hopcroft–Karp, which would be O(E sqrt(V)) ≈ 450k * sqrt(150k) ~ 450k*387 ≈ 174M, perhaps borderline but maybe okay in C++ but not Python. So we need a simpler greedy approach?
Observation: Each boxer can take only contiguous integer weights (range of length 3). The goal is to assign distinct integer weights to as many boxers as possible. This is reminiscent of scheduling/interval matching: we have items that can take values from a set of integers, we want to assign distinct values. This can be solved by a greedy algorithm: sort boxers by something, then assign the smallest possible weight?
Consider we treat each boxer's possible weights as a small set. To maximize number, we want to assign distinct weights, preferably using as low weights as possible? However, we have many possible weight values.
We can consider the problem as: For each integer weight w from 1 to max, we can assign at most one boxer whose allowed set contains w. We want to maximize total assignments.
This is essentially a bipartite matching where right side has capacity 1 per weight. We can solve by greedy: sort boxers by the maximum weight they can take? Actually classic problem: given intervals (or sets) of possible values, assign distinct numbers to maximize assignments; a greedy that tries to assign each boxer the smallest possible weight that is not taken (like a matching in a bipartite graph where left side order arbitrary) can be optimal if we process boxers in a specific order? Not necessarily: if we have two boxers: one can take {1,2}, other can take {1}. The optimal is assign boxer1:2, boxer2:1 → total 2. If we greedily assign the first boxer the smallest available (1), then second boxer has no available → total 1. So order matters. But if we process boxers sorted by the rightmost (max) possible value (or by something) we can apply a greedy that assigns the smallest available ≥ lower bound? That works for intervals? Actually classic problem: given intervals [l_i, r_i] where each interval can be assigned a point within it, and we want to assign distinct points to maximize number of intervals assigned. That's like maximum cardinality matching between intervals and points (discrete). If points are integer and each interval can take any integer in its range, a greedy works: sort intervals by r_i (right endpoint), then for each interval in increasing order, assign the smallest available point >= l_i (if possible). That maximizes number of assignments. This works because it's like scheduling to maximize number of tasks with unit processing time on a single machine with time slots. Here each interval represents a continuous range of integers.
But in our problem, each boxer's allowed set is not necessarily an interval; it's up to three values: {a_i-1, a_i, a_i+1} (if valid). That is like three points, not a continuous range. However, note that a_i is integer, so these three values are consecutive integers: indeed {a_i-1, a_i, a_i+1} (with bounds). So it is actually a contiguous range of length 3, but only if we allow any integer in between? Actually it's exactly the set of three integers, but they are contiguous: it's the interval [a_i-1, a_i+1] ∩ ℕ, but it's not all integers between because it's only those three? Wait: "can change the weight by no more than 1" means final weight = a_i + d, where d ∈ {-1,0,1} (if >0). So indeed possible values are exactly a_i-1, a_i, a_i+1 (provided they are ≥1). So it's a set of up to 3 integers, but they are consecutive. So it is a small contiguous interval: from L_i = max(1, a_i-1) to R_i = a_i+1 (but note if a_i=1, L_i=1? Actually 0 not allowed so max(1, a_i-1) =1; but then allowed values: 1? Actually a_i=1, possible: 0? no, must be positive, so cannot be 0. So allowed: 1 (stay), 2 (increase). So the set is not exactly [L_i, R_i] because if L_i= max(1, a_i-1) and R_i = a_i+1, then the interval would include L_i+1? For a_i=1: L_i=1, R_i=2 → interval {1,2} which matches allowed. For a_i=2: L_i=1, R_i=3 → interval {1,2,3}. But allowed is {1,2,3}? Actually a_i=2: allowed: 1 (decrease),2 (stay),3 (increase) -> yes exactly {1,2,3}. So indeed the allowed set is exactly all integers from max(1, a_i-1) to a_i+1 inclusive. Because the difference between a_i-1 and a_i+1 is 2, so it's full range of three integers except when a_i=1, L_i=1, R_i=2 (range length 2). Similarly, if a_i is large, but no upper bound except 150001? Actually a_i ≤ 150000, a_i+1 ≤ 150001, that's allowed. So the allowed set is exactly the integer interval from L_i = max(1, a_i-1) to R_i = a_i+1 (inclusive). That is a contiguous interval of length either 2 or 3 (or maybe 1? if a_i=0? but a_i≥1). For a_i=1: length 2; for a_i>=2: length 3. So indeed each boxer's possible weights form an interval of length 2 or 3. Good! So we can treat each boxer as having interval [L_i, R_i] (discrete, inclusive). Then we need to assign distinct integer points to as many boxers as possible, each boxer assigned a point within its interval.
Thus it's exactly the classic problem: given intervals on a line (with integer endpoints), assign distinct integer points to maximize number of intervals assigned. This is a well-known problem solvable by greedy: sort intervals by right endpoint; iterate; maintain the smallest available point >= left endpoint that hasn't been assigned; assign that point. But wait: the classic problem is where we have to assign a point to each interval such that no two intervals share the same point; we want to maximize the number of intervals assigned. The greedy algorithm that processes intervals in order of increasing right endpoint, and for each interval assign the smallest point ≥ L_i that hasn't been used, is optimal. That's essentially a matching in bipartite graph where intervals are on left and integer points on right, and the intervals are intervals. This is a special case of bipartite matching with convex structure (interval scheduling) where greedy works.
But is the classic problem always about assignment of distinct points (like "interval scheduling with resource constraints")? Actually there are two variants: (1) select a maximum set of intervals that do not overlap (select intervals). That's different. (2) assign each interval a distinct point within it; maximize number of assignments. This is equivalent to finding maximum matching in interval graph. There's known result: the greedy algorithm (sort by right endpoint, assign the earliest available point) yields maximum cardinality. This can be proven by exchange argument or by reducing to min-cost flow? But I recall a problem "assign lectures to classrooms" or "assign tasks to time slots" which is similar to interval coloring. Actually, assigning points to intervals is like "hitting" each interval with a point, but we want distinct points. It's also like "matching intervals to points". In many competitive programming problems, the greedy works.
Let me think carefully: We have intervals (Li, Ri). We want to assign integer points (weights) such that each interval gets one point, points distinct. We want to maximize number of intervals assigned. This is similar to "Maximum bipartite matching when left side intervals" can be solved by greedy because the right side points are linearly ordered and intervals are contiguous. It's like the problem of scheduling tasks on a single machine where each task has a release time (Li) and deadline (Ri) and we need to assign a time slot (integer) to each task, at most one task per slot, maximizing number of tasks scheduled. The greedy algorithm for that is: sort tasks by deadline, and for each task, assign the latest possible slot that is ≤ Ri and not taken? Or assign earliest? Actually scheduling to maximize number of tasks with unit processing times and release times/deadlines: we want to schedule as many tasks as possible. A known algorithm is: sort tasks by deadline, then for each task, assign it to the earliest available time >= release time; but that may fail to maximize number? Let's consider simple example: tasks: [0,1] and [0,1]. Two tasks both have Li=0, Ri=1. With points 0 and 1 available. Greedy by deadline: sort by Ri=1,1. Process first: assign smallest available >=0, which is 0. Second: smallest available >=0 is 1, but 1 <=1, so assign 1. Both scheduled. Good. Another: tasks: [0,1] and [1,1]. First task (deadline 1): assign smallest available >=0 -> 0. Second task (deadline 1): assign smallest available >=1 -> 1 (available). Good. Another: tasks: [0,1] and [0,0]. Greedy sort by deadline: tasks: [0,0] (deadline 0), [0,1] (deadline 1). Process first: assign smallest >=0 -> 0. Second: smallest >=0 that's not taken? 0 taken, next 1, and 1 <=1, assign 1. Both scheduled. Works.
Counterexample? I think the greedy algorithm that sorts by right endpoint and assigns the smallest available point >= left endpoint is optimal for maximizing number of intervals assigned distinct points. I've seen this in many problems e.g., USACO "help cross" (assign cows to times) or "Minimum number of points to cover intervals" is different. Actually we need to assign points to intervals; it's like a matching between intervals and points. The greedy works because the intervals are "convex" and points are unit capacity. There's a known result: the bipartite graph formed by intervals is a "convex bipartite graph" (left vertices are intervals, right vertices are points, edges if point lies within interval). For convex bipartite graphs, a simple greedy (like sorting left vertices by right endpoint and assigning smallest available right vertex) yields a maximum matching. Indeed, that is a property of convex bipartite graphs: the greedy algorithm yields maximum matching if we process left vertices in order of non-decreasing right endpoint, and for each left vertex, match it to the smallest available right vertex that is >= left endpoint. This is standard. So we can apply that.
Thus solution: For each boxer i, compute L_i = max(1, a_i-1), R_i = a_i+1 (but careful: if a_i=150000, R_i=150001, which is allowed. Also note that a_i up to 150000, so R_i up to 150001). Then we have intervals [L_i, R_i]. We want to find maximum number of intervals we can assign distinct integer points. So we sort intervals by R_i ascending (if tie, maybe by L_i ascending? but not necessary). Then we iterate, maintain a set of used points (or just a pointer for next available? Since we assign smallest available >= L_i, we need to know used points up to some range. But we can maintain a boolean array of used weights (size up to 150001+1 = 150002? Actually max weight = max_i R_i <= 150001; plus maybe we need weight 150001? Yes. So array size 150002 maybe. We can maintain a variable that indicates which weights are taken.
But the greedy algorithm: For each interval in sorted order, we want to assign the smallest integer w such that w ∈ [L_i, R_i] and w is not yet assigned. If such w exists, assign it, mark used, count++. If no such w, skip interval (don't assign that boxer). This greedy yields maximum matching.
Let's test on sample:
Sample1: a = [3,2,4,1]. Compute intervals:
3 -> L=2, R=4 (since a_i-1=2, a_i+1=4)
2 -> L=1, R=3
4 -> L=3, R=5
1 -> L=1, R=2
Sort by R: (1,2) R=2; (2,3) R=3? Actually need to list: intervals:
i1: [2,4] R=4
i2: [1,3] R=3
i3: [3,5] R=5
i4: [1,2] R=2
Sorted by R: i4 (R=2), i2 (R=3), i1 (R=4), i3 (R=5)
Process:
i4 [1,2]: smallest available >=1: 1 not used -> assign 1
i2 [1,3]: smallest available >=1: 1 used, so 2? 2 not used? Actually 2 not used yet (only 1). 2 ∈ [1,3] -> assign 2
i1 [2,4]: smallest available >=2: 2 used, 3? 3 not used -> assign 3
i3 [3,5]: smallest >=3: 3 used, 4? 4 not used -> assign 4
All assigned -> count=4. matches.
Sample2: a = [1,1,1,4,4,4]
Compute intervals:
for 1: L=1,R=2 (since a=1, L=max(1,0)=1, R=2)
for 1: same
for 1: same
for 4: L=3,R=5 (since a=4, L=3,R=5)
for 4: same
for 4: same
We have intervals: three intervals [1,2] and three intervals [3,5].
Sorted by R: three [1,2] R=2, three [3,5] R=5.
Process first [1,2]: assign 1.
Second [1,2]: smallest available >=1: 1 used, next 2 -> assign 2.
Third [1,2]: smallest >=1: 1,2 used; next candidate 3? but 3 > R=2, not allowed -> skip (can't assign).
Now three [3,5] intervals:
First [3,5]: smallest >=3: 3 not used -> assign 3.
Second [3,5]: smallest >=3: 3 used, next 4 -> assign 4.
Third [3,5]: smallest >=3: 3,4 used, next 5 -> assign 5.
Total assigned: 2 + 3 = 5. matches sample output.
Thus greedy works.
Implementation details: n up to 150k, weight range up to 150001. We need to efficiently find smallest unused integer ≥ L_i within [L_i, R_i]. Since we process intervals sorted by R_i, we could maintain a boolean array used[1..maxWeight] and for each interval, iterate from L_i upward until find a free slot, but that could be O(range) per interval worst-case, too slow. But we can use a data structure to find next available slot, like a union-find (disjoint set) for "next free slot". Classic technique: maintain an array next_free[w] which points to the next candidate weight that might be free (or itself if free). When we assign a weight w, we set next_free[w] = w+1 (or union with next). Then to find the smallest free >= L, we do find(L) (using DSU with path compression). However, the weights are limited (max 150001+ maybe small). So we can predefine a DSU with indices from 1 to maxW+1 (sentinel). For each query, we find root = find(L). If root <= R_i, then that weight is free, assign it, then union root with root+1 (i.e., set parent[root] = find(root+1)). If root > R_i, then no free weight in interval.
Alternatively, we can use a balanced BST (like a set of free weights) and each time we assign we remove from set. But we need to find smallest free >= L_i. We could maintain a sorted set of unassigned weights? Actually initially all weights are free, we gradually assign some. We need to query for the first free weight >= L_i. That's like a "successor" query. Using a set of free weights (like a TreeSet) we can do lower_bound(L_i). But the number of weights is up to 150001, which is moderate; we can maintain a boolean array and use DSU for near O(alpha). Simpler: maintain a bitset and a pointer? Since we process intervals sorted by R_i, the assigned weights will be mostly small? Not necessarily. But we could also just simulate using a set: initially populate a set with all weights 1..maxW (maybe 150001). For each assignment, we find it = free_set.lower_bound(L_i). If it exists and *it <= R_i, assign, then erase it. Else skip. This is O(log maxW) per interval. With n up to 150k, O(n log n) = fine. Python has sortedcontainers? Not built-in. But we can implement using bisect on a sorted list? However, deletions would be O(n). So DSU approach is simpler and O(alpha). So use DSU (union-find) for next free.
But careful: The maximum weight we might need is up to max of R_i. Since a_i ≤ 150000, R_i ≤ 150001. So we can set maxWeight = 150002 (to have sentinel for root+1). We'll use DSU parent array of size maxWeight+2 maybe.
Alternatively, we could also use an array "next" initialized to i. Then for find we compress. This is simpler.
Pseudo:
Read n, list a.
For each a_i, compute L = max(1, a_i-1), R = a_i+1.
Store intervals as tuple (R, L) or (L, R) but we need sort by R.
Sort intervals by R ascending (and maybe by L ascending secondary, but not required).
maxW = max(R_i) over all intervals. Since a_i <= 150000, we know maxW = 150001. But we can compute for safety.
Initialize DSU: parent[w] = w for w from 1 to maxW+1 (maxW+1 as sentinel representing "none"). Actually we need to be able to find next free weight; if weight w is taken, we set parent[w] = w+1. So find(w) returns the smallest free >= w, if any, up to maxW+1 (where maxW+1 is considered out-of-range). So we need parent[maxW+1] = maxW+1 (sentinel) and treat that as no free weight.
count = 0.
For each interval (L,R):
w = find(L)
if w <= R:
count += 1
# mark w as used: union w with w+1
parent[w] = find(w+1) # or set parent[w] = w+1 and later compress via find; but typical: union(w, w+1)
else: skip.
Print count.
Now we must ensure the DSU find works efficiently.
Implementation of DSU for next free:
We can have an array nxt of size maxW+2 (indices 1..maxW+1). Initially nxt[i] = i.
Define function find(x):
if nxt[x] != x: nxt[x] = find(nxt[x])
return nxt[x]
To mark w as used:
nxt[w] = find(w+1) # because now w is occupied, next free from w is w+1's free.
But note: after marking w as used, future find(w) will go to find(w+1). So correct.
The sentinel maxW+1: find(maxW+1) = maxW+1. So if w = maxW+1, that means no free weight. So when we check w <= R, if R is maxW (150001), then w = maxW+1 would be >R, so skip.
Edge Cases:
a_i = 150000 -> R = 150001. That's within our array size if we set maxW = 150001. So need nxt[150001] initially 150001; if we assign it, we set nxt[150001] = find(150002). But we didn't allocate 150002? For sentinel, we need index up to 150002 to avoid index error. Since we may call find(w+1) for w=150001, we need nxt[150002] defined. So we set maxW = 150001 (largest possible R). We'll allocate array size maxW+2 = 150003 maybe. Initialize nxt for indices 1..maxW+1 inclusive? Actually we need nxt[maxW+1] for weight maxW+1 (which is 150002) as sentinel. But our actual weight domain is 1..150001. When we assign 150001, we set nxt[150001] = find(150002). 150002 is beyond max weight, but we need it to be a valid index representing "no free". So we allocate array size = max_possible_R + 2 = 150001 + 2 = 150003. We'll initialize nxt[i] = i for i = 1..max_possible_R+1 (i.e., up to 150002). Then find works.
Alternatively, we can just use a set approach: maintain a set of free weights as a sorted list? Not efficient to delete.
But DSU is simple.
Complexities: O(n log n) for sorting, plus near O(n α) for DSU. Good.
Now ensure correctness: The greedy algorithm described is optimal for convex bipartite matching. We can also think of it as: we want to maximize number of assigned intervals; this is equivalent to minimizing number of unassigned intervals. The greedy by right endpoint ensures we don't "waste" slots that could be used by later intervals.
But let's prove quickly: In the standard problem of assigning points to intervals, the greedy algorithm that processes intervals in order of increasing right endpoint and assigns the smallest available point that is >= left endpoint yields a maximum matching. This can be proven by exchange: Suppose we have an optimal assignment that differs from greedy. Consider the first interval in sorted order where greedy chooses a point p, and optimal chooses a point q (maybe none). If greedy assigned p but optimal didn't assign any, then we can modify optimal to assign p to this interval (since p is free in optimal because greedy uses p later? Need careful). Actually standard proof: The greedy algorithm is optimal because it always makes a choice that does not preclude optimality; the matching produced is maximum because the set of points used is a system of distinct representatives with minimal "conflict". I recall that this is essentially the same as the algorithm for maximum bipartite matching in an interval graph, and it's known to be optimal.
Let's test on edge cases: Suppose intervals: [1,2] and [2,3]. Greedy sort by R: [1,2] (R=2), [2,3] (R=3). Process first: assign smallest >=1 -> 1 (or maybe 1 is available) assign 1. Second: smallest >=2 -> 2 (available) assign 2. Both assigned. Alternative assignment could be 2 and 3 or 1 and 3. Works. If we have [1,3] and [2,2] and [2,2] (two intervals exactly [2,2]). Sort by R: [2,2] (R=2), [2,2] (R=2), [1,3] (R=3). Greedy: first [2,2]: assign 2. second [2,2]: smallest >=2 -> 2 taken, next is 3 >2 so cannot assign -> skip. third [1,3]: assign smallest >=1 -> 1 (free) assign 1. Total 2. Optimal could be assign 1 and 2 to the two [2,2]? Actually [2,2] can only take 2. So only one can take 2. The other could take nothing. So maximum 2: either one [2,2] gets 2 and [1,3] gets 1; or maybe [1,3] gets 3 and one [2,2] gets 2; still 2. So greedy yields 2. Good.
Another: intervals: [1,1], [1,2]. Sort by R: [1,1] (R=1), [1,2] (R=2). Greedy: first assign 1; second assign smallest >=1 -> 1 taken, next 2, assign 2. Both assigned. Good.
If we reverse order: processing by left? Might fail.
Thus algorithm is sound.
Potential pitfalls:
Ensure we treat intervals correctly: For a_i=1, L=1, R=2 (since a_i+1=2). For a_i=0 not possible.
For a_i=150000, R=150001, that's allowed.
What about weight 0? Not allowed, so L must be at least 1.
Also note that a_i can be as high as 150000, but the problem statement says "It is possible that after some change the weight of some boxer is 150001 (but no more)." So we respect that.
Now memory: DSU array of size ~150003, fine.
Implementation steps in Python:
import sys
read n (int)
read list of a (list of ints)
intervals = []
for ai in a:
L = ai-1 if ai-1 >= 1 else 1 # max(1, ai-1)
R = ai+1
intervals.append( (R, L) ) # store as (R, L) for sorting by R
intervals.sort() # sorts by R first, then L if tie (since we stored (R, L))
Determine maxR = intervals[-1][0] if intervals else 0; but we know it's up to 150001. We'll set MAX_W = 150001 + 1 (since we need sentinel up to 150002). Could just set MAX = 150002 + 5? To be safe, 150005.
maxW = 150002 # because we need indices up to 150001 (weight) and 150002 sentinel
Actually we need sentinel = max possible R + 1. max possible R = max(ai+1). Since ai <= 150000, maxR <= 150001. So sentinel = 150002.
So allocate parent = list(range(150003)) maybe 150005 to be safe.
count = 0
for (R, L) in intervals: # careful: we stored (R, L)
w = find(L)
if w <= R:
count += 1
parent[w] = find(w+1) # union with next
print(count)
But note: We stored intervals as (R, L) to sort by R. So in loop we have R and L. But we need to use them accordingly: w = find(L); if w <= R: assign.
We also might need to consider that some intervals have L > R? Not possible because L = max(1, a_i-1) and R = a_i+1. For a_i=1, L=1,R=2 okay. For a_i=0 not possible. So always L <= R.
Check large n: sorting O(n log n) fine.
Potential issue: Python recursion depth for find? DSU find recursion might cause recursion depth if path long (up to 150k). We can implement iterative find to avoid recursion:
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression? but easier recursion but might exceed recursion limit. Better implement iterative with while loop.
We'll implement iterative:
def find(x):
root = x
while parent[root] != root:
root = parent[root]
# compress path
while parent[x] != x:
nxt = parent[x]
parent[x] = root
x = nxt
return root
Or simpler: recursion with sys.setrecursionlimit(200000) should be fine because depth limited by path length but with compression it's unlikely to be deep. However, Python recursion limit default 1000; DSU find recursion can cause deep recursion if not compressed well. But if we implement recursion and use path compression (recursive calls), each find might call itself recursively along a chain. Initially chain length could be up to 150k if we always union consecutive numbers? Consider marking weights from 1 upward. Suppose we assign weight 1, then we set parent[1]=find(2). find(2) returns 2 (since not assigned). So chain: parent[1]=2. Then assign weight 2: find(2) returns 2, then we set parent[2]=find(3)=3. So chain becomes 1->2->3->... up to k. Later, find(1) would traverse chain of length k. In recursion, this could cause recursion depth error if k > 1000. So recursion is unsafe. Use iterative.
Implement iterative find:
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
Simpler: use while loop with path compression:
def find(x):
root = x
while root != parent[root]:
root = parent[root]
# path compression
while x != root:
nxt = parent[x]
parent[x] = root
x = nxt
return root
We'll adopt this.
Alternatively, we can use a simple array "next_free" and not compress, but just iterate? That would be O(n^2) worst-case. So DSU is needed.
But note that we only do union operations that always point to a larger index (w+1). This results in a structure where each set's root is the smallest free index >= some bound. Actually it's a standard "disjoint set for next free" which often uses a recursion or while loop but with path compression it's fine.
We can also use an array and a while loop to find next free without compression but with memoization? Not efficient.
Thus implement iterative DSU.
Now, we need to consider that we have many intervals (150k) and we may skip many. Complexity fine.
Check potential corner case: weight values up to 150001, so we need array size at least 150002+? For sentinel 150002, but we also might call find(150002). When we assign weight 150001, we will set parent[150001] = find(150002). So find(150002) must be defined. So allocate size = 150003 (indexes 0..150002). But we never use index 0, but we could include it. We'll allocate size = max_possible_R + 2 = 150001 + 2 = 150003. To be safe, we can compute actual maxR from intervals and allocate accordingly to save memory, but 150003 is trivial.
Now, question: Could there be a case where a_i+1 > 150001? The problem says "It is possible that after some change the weight of some boxer is 150001 (but no more)." That implies that we cannot exceed 150001. But a_i <= 150000, so a_i+1 <= 150001. So fine.
Now, we must ensure that we respect the constraint that weight must remain positive: L = max(1, a_i-1) ensures that.
Now, we need to output the maximum number of boxers we can assign distinct weights.
Thus the algorithm seems correct.
But wait: Is there any nuance about the fact that each boxer can change weight by at most 1, not exactly the whole interval? As argued, it's exactly the interval. So correct.
If n=2, a=[1,1] => intervals [1,2] and [1,2]. As earlier, can assign 1 and 2 -> 2.
If n=2, a=[1,2] => intervals: [1,2] and [1,3]? Actually a1=1: [1,2]; a2=2: L=1,R=3. Sorted by R: [1,2] (R=2), [1,3] (R=3). Greedy: assign first: 1; second: smallest >=1 -> 1 taken, next 2, 2 <=3 assign 2 -> both assigned. So 2.
If n=2, a=[1,150000] => intervals: [1,2] and [149999,150001]. Distinct intervals far apart, both assign: first assign 1, second assign 149999? Actually second: find(149999) = 149999, assign 149999 (since free). So 2.
If n=3, a=[2,2,2] => intervals: each [1,3]. Sorted by R=3 for all. Greedy: first assign smallest >=1 -> 1; second assign smallest >=1 -> 2; third assign smallest >=1 -> 3; all assigned -> 3. Indeed possible: assign weights 1,2,3 respectively. Yes.
If n=3, a=[1,1,1] => intervals: each [1,2]. Max assign: 2, because only two distinct weights within [1,2]. Greedy: first assign 1; second assign 2; third: smallest >=1 -> 1 and 2 taken, next 3 >2 -> skip. So 2. That seems correct. But could we assign a weight of 0? No.
Thus correct.
Now let's consider a trick: Could there be a case where using a weight beyond the interval but by "changing weight by no more than 1" we can only do ±1, so interval is fixed. So no.
Thus solution stands.
Now we implement in Python.
But we need to be careful about input size: Use sys.stdin.read() to parse quickly.
Implementation details:
code
def solve():
import sys
data = sys.stdin.read().split()
if not data: return
it = iter(data)
n = int(next(it))
a = [int(next(it)) for _ in range(n)]
intervals = []
for ai in a:
L = ai-1 if ai>1 else 1 # max(1, ai-1)
R = ai+1
intervals.append((R, L)) # sort by R
intervals.sort()
maxR = intervals[-1][0] if intervals else 0
maxW = maxR + 1 # sentinel
size = maxW + 2 # allocate a bit more
# Actually we know maxR <= 150001, so we can set fixed size = 150005
# but for safety we can compute.
# Use fixed size 150005 to avoid computing.
MAX = 150002 + 5 # but we need index up to maxR+1 (maxR<=150001, so maxR+1=150002). So allocate 150005
parent = list(range(150005))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
count = 0
for R, L in intervals:
w = find(L)
if w <= R:
count += 1
parent[w] = find(w+1)
print(count)
But using fixed size 150005 is fine. But note that if we allocate large array of size 150005, it's fine.
But we must be careful: when w+1 might exceed allocated size? If w = 150001, then w+1 = 150002, and we have parent[150002] defined (since size 150005 > 150002). If w = 150002? That could happen only if we try to assign a weight that is not allowed? Actually w is only assigned if w <= R and R <= 150001, so w <= 150001. So w+1 <= 150002, safe. Also find(150002) will be called; we have parent[150002] defined.
Now, verify with example: For a_i=150000, R=150001, L=149999. In find(L) we may need to traverse up to 150001? But fine.
Now, is there any possibility that we need weight 0? No.
Thus code works.
But is the greedy algorithm optimal for this specific problem where intervals are of length 2 or 3? Yes.
Let's test with random small cases by brute force to be absolutely sure. We can't run here but mentally I'm convinced.
Now, ensure we haven't missed that each boxer can choose to not change weight? Yes, that's included as weight a_i.
Now, any possibility to assign weight that is not integer? No, weights are integer.
Thus solution is correct.
Now, time complexity: O(n log n) for sorting, plus O(n α(maxW)) for DSU. With n=150000, this is fast.
Memory: O(maxW + n). Good.
Now we produce final answer.
But note: In the DSU, we used parent array of size 150005. For safety, we can compute maxR and allocate accordingly, but that's fine.
Potential pitfalls: The intervals list may contain duplicates; sorting works.
Edge Cases: n=0? Not possible, n>=1.
Now, I'll produce the final solution explanation and code.
Wait, I recall a known Codeforces problem: "Boxers" (CF 230B? Actually I recall problem named "Boxers" from Codeforces Round #...). Indeed it's Codeforces problem 230B? Not sure. But the typical solution is exactly this greedy with a set or DSU.
Thus final answer: implement as described.
Now produce final response. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
a = [int(next(it)) for _ in range(n)]
code
intervals = []
for ai in a:
L = ai - 1 if ai > 1 else 1 # max(1, ai-1)
R = ai + 1
intervals.append((R, L)) # store (right, left) to sort by right endpoint
intervals.sort() # increasing right endpoint
# maximum possible weight is 150001, sentinel is 150002
MAX = 150002 + 5 # a little extra safety
parent = list(range(MAX))
def find(x: int) -> int:
# iterative find with path compression
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
count = 0
for R, L in intervals:
w = find(L)
if w <= R:
count += 1
parent[w] = find(w + 1) # mark w as used
print(count)