Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).
Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.
Input
First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies.
Second line contains sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 109) — amounts of candies in each pile.
Output
Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.
Examples
Input
4
12 14 30 4
Output
2
Input
6
0 0 0 0 0 0
Output
6
Input
6
120 110 23 34 25 45
Output
3
Input
10
121 56 78 81 45 100 1 0 54 78
Output
0
Note
In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).
In second example you should add two candies to any three piles.
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 read problem: we have n piles (even). In each move, we can either add one candy to a pile, or remove one candy from a pile (if at least one). Goal: after operations, exactly n/2 piles have candy counts that are perfect squares (including 0? Let's check: 0 is a square of integer 0, so it is a perfect square. But note: definition: "Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer." So Borya does not like squares. So piles that are squares should be exactly n/2 and non-squares exactly n/2.
The input includes a_i could be 0. In example 2: n=6, all zeros. 0 is square. So currently all 6 piles are squares, but we need exactly 3 squares and 3 non-squares. So we need to change some piles from square to non-square or vice versa by modifying their counts. Each modification (add or remove) costs 1 move per candy change. We want minimal total moves.
We need to decide which piles become squares and which become non-squares after modifications. We can modify each pile's count arbitrarily (by adding or removing candies) but each unit change costs 1. We want minimal total cost to achieve exactly half squares, half non-squares.
Observations:
For each pile, if its current count a_i is already a perfect square, we can either keep it as square (cost 0) or change it to a non-square. To become non-square, we need to modify the count to a non-square number. The minimal cost to change a square to a non-square? We can add 1 or subtract 1 (if possible) to get a non-square. But careful: If a_i = 0, we cannot subtract because we need at least one candy to remove. So for a_i=0, only option is to add 1 (making it 1, which is square? 1 is also square! Actually 1 is square (1^2). So we need to consider minimal steps to convert a given number to a non-square. Similarly, for a non-square we can either keep it (cost 0) or convert to a square (cost = distance to nearest perfect square). Because we can add or remove candies to reach the nearest perfect square (maybe multiple steps). But we need to also consider the possibility of converting a square to a non-square by more than one step? Because maybe the minimal steps to become non-square could be to reach a non-square number with minimal moves. For square numbers, the nearest non-square might be either +1 or -1 (if a_i >0) but sometimes both +1 and -1 may also be squares? Let's check: squares: 0,1,4,9,16,25,... The neighbors: For 0: +1=1 (square), +2=2 (non-square). So for 0, minimal steps to non-square is 2? Because moving 1 step leads to 1 which is square. So need at least 2 steps to reach 2 (non-square). Could also go to -1? Not allowed. So minimal cost for a square to become non-square may be >1. Similarly for 1: -1=0 (square), +1=2 (non-square) => minimal cost is 1 (since 2 is non-square). For 4: 3 (non-square) by -1, cost 1; also 5 non-square? 5 is non-square, cost 1 as well. Actually 4's neighbors: 3 and 5 both non-squares, so cost 1. For 9: 8 non-square, cost 1; 10 non-square cost 1. For 16: 15 non-square, cost 1; 17 non-square cost 1. So for squares >0, it seems usually -1 or +1 yields a non-square? But is there any square where both neighbors are squares? That would require squares that are consecutive numbers, impossible except 0 and 1? Check 0: neighbors -1 (invalid) and 1 (square). So for 0, both valid neighbor(s) is square. For 1: neighbors 0 (square) and 2 (non-square). So at least one neighbor is non-square. Actually for any positive integer, there's no two consecutive squares except 0 and 1? 0 and 1 are consecutive but 0 and 1 are both squares; but if we consider positive squares: 1,4,9,... Difference between squares is increasing: (n+1)^2 - n^2 = 2n+1 >=3 for n>=1. So for square k^2 with k>=2, the distance to next square is >2, so both neighbors (k^2 -1 and k^2 +1) are not squares. For k^2 = 1, neighbor 0 is square but neighbor 2 is non-square. So indeed for all squares >0, the minimal cost to become non-square is 1. For 0, the minimal cost is 2? But can we go to 2? That's +2 steps. Could we go to -? No. So cost 2. Also check if there is any other square where minimal steps to non-square is >1? No, because for k>=1, k^2-1 is not square (since (k-1)^2 = k^2-2k+1, for k>=2, (k-1)^2 <= k^2-3 < k^2-1, so k^2-1 not square; for k=1, k^2-1=0 is square but we have k^2+1=2 non-square). So only 0 is special.
But also consider possibly making a square become a non-square by moving to a non-square that is further but maybe more convenient? Not needed for minimal cost per pile when we decide to convert. So for each pile, we can compute:
cost_to_make_square: if a_i is already a perfect square, cost 0 to keep square; if not, we need to change it to a perfect square. The minimal number of moves to turn a_i into a perfect square is: distance to nearest perfect square (i.e., min_{k} |a_i - k^2|). However, careful: if a_i = 0, it's square, cost 0. For non-square, we need the minimal steps to a square. But we must also consider that when we change from a non-square to a square, we may consider also possibility of making it a square by going through multiple steps? The minimal steps is simply the absolute difference to the nearest square. Because we can add or remove step by step to reach exactly that square. So that is correct.
cost_to_make_non_square: if a_i is not a perfect square, cost 0 to keep non-square; if a_i is a perfect square, we need to change it to a non-square. For a_i > 0 (and square), cost = 1 (since we can go to a_i+1 or a_i-1, both non-square, except for a_i=0, cost=2? Actually 0: we can add 1 to get 1, which is square, not good; add 2 to get 2, non-square, cost 2. There's no subtract. So cost = 2). However, is there any case where a_i is a square and we could convert to non-square with 0 moves? No, because it's square, so need change.
But wait: what about a_i = 1? 1 is square. To make non-square, we could go to 2 by adding 1, cost 1. So cost 1.
Thus cost_to_make_non_square for squares: if a_i == 0, cost = 2; else cost = 1.
But is there any other special scenario? Could a_i be a perfect square but we could also turn it into a non-square by removing all candies to 0? But 0 is square, so not allowed. So must move to non-square.
Thus for each pile i we have two possible states after modification:
Square (S): cost = cost_to_make_square(i)
Non-square (N): cost = cost_to_make_non_square(i)
We need exactly n/2 piles in S, n/2 in N. We need to assign each pile to either S or N, minimizing total cost.
This is a classic selection problem: we have for each pile two costs. Want to choose exactly half to be S, half N. The minimal total cost is sum of base costs (cost to keep as is) plus maybe adjustments? But we can compute for each pile: if we assign it to its current type (square or not), cost = 0. If we need to change, cost = some positive number.
But we must choose assignment such that total S count = n/2.
We can approach by considering:
Let count_current_squares = number of piles that are currently perfect squares (call it c_s). Let count_current_non = n - c_s.
We need final squares = n/2. So we need to either increase number of squares (if c_s < n/2) or decrease (if c_s > n/2). When c_s < n/2, we need to convert some non-squares into squares; when c_s > n/2, we need to convert some squares into non-squares; if equal, we may still need to adjust if some conversions are zero? Actually if equal, but some piles might have zero cost to convert? But if current number matches, we can keep them all, cost 0, unless some piles are not able to stay? They are already squares or non-squares, so we can keep them at zero cost. So answer would be 0. So only mismatches cause need to change.
But careful: Suppose c_s = n/2, but some squares have cost 0 to stay square, and non-squares cost 0 to stay non-square, so overall cost 0. So answer is 0. So the sample 4: Input: 10 numbers, many squares? Actually output 0, so initial condition satisfied.
Thus algorithm: if c_s == n/2, answer 0.
Otherwise we need to convert some piles from one type to the other.
But is it always optimal to only convert piles from the surplus type to the deficit type? Because we could convert both ways: e.g., if we have too many squares, we can convert some squares to non-squares; but also convert some non-squares to squares, which would further increase squares count, making it worse. So to fix count, we should only convert from surplus to deficit. That is, if c_s > n/2, we need to change some squares into non-squares; if c_s < n/2, we need to change some non-squares into squares.
Thus we only need to consider converting piles from the surplus type to the deficit type. However, we need to choose which piles to convert, minimizing total cost of conversion. So we need to know for each pile of the surplus type, the cost to convert it to the deficit type. For squares (surplus), cost = cost_to_make_non_square; for non-squares (surplus? Actually if c_s < n/2, deficit is squares, so we need to convert non-squares to squares, cost = cost_to_make_square). So we take the piles of the type we have too many of, compute conversion cost for each, sort ascending, and pick the smallest k = |c_s - n/2| piles, sum their costs, output that sum.
But careful: In some cases, could it be beneficial to convert some piles from both types? For example, suppose we have c_s > n/2, but converting a square to non-square costs high (say 100), but converting a non-square to square costs low (say 1). Could we convert a non-square to square (increasing squares count further) and also convert a square to non-square (decreasing squares count) to keep net change zero? That would increase total conversions by 2 but net count remains same? Actually if c_s > n/2, we need to reduce squares count by d = c_s - n/2. If we convert one square to non-square, that reduces squares count by 1. If we also convert a non-square to square, that increases squares count by 1, so net change 0. To achieve net reduction of d, we could convert d squares to non-squares and also maybe convert some other pairs? That would just increase cost, not help. Unless converting a square to non-square is expensive, but converting a non-square to square is cheap, and by doing a swap we could lower total cost? But you cannot "swap" types without net change; you need to achieve a specific net change. If we need to reduce squares by d, we could convert d squares to non-squares; that's necessary. If we additionally convert some non-square to square, we would have to offset by converting another square to non-square, resulting in extra cost. So total cost would be at least the sum of the d smallest conversion costs from squares to non-squares. Converting any extra pairs would add more cost. So minimal is exactly that.
But consider that some piles might have zero cost to convert? For squares, cost to make non-square is 1 or 2, not 0 (since if it's square, to become non-square must change at least 1 candy, so cost >=1, except maybe if it's 0? cost 2). For non-squares, cost to make square could be zero? Only if it's already a square, but then it wouldn't be non-square. So cost_to_make_square for a non-square is at least 1? Wait, could a non-square be at distance 0 to a square? No, because then it would be a square. So minimal distance to a square is at least 1. However, is it possible that a non-square is exactly 0? 0 is square, so non-square means not square, so a_i>0? Could be 0? 0 is square, so non-square numbers are numbers that are not perfect squares, including 0? Actually 0 is a perfect square (0^2=0). So 0 is a square. So a_i can be 0 and it's square. So non-square numbers are >0 and not perfect squares, or maybe negative? But a_i >=0, so non-square numbers are positive numbers that are not perfect squares. So for a non-square, the distance to the nearest perfect square is at least 1. So cost_to_make_square is at least 1. So all conversion costs are positive.
Thus the greedy selection of smallest conversion costs works.
But we need to verify with sample inputs.
Example 1:
n=4, a=[12,14,30,4]
Compute squares: 4 is perfect square (2^2). Others: 12,14,30 are non-squares. So c_s=1, n/2=2, need to increase squares by 1. So convert one non-square to square. Compute cost_to_make_square for each non-square:
12: nearest square: 9 (diff=3) or 16 (diff=4) -> min=3.
14: nearest: 9 diff5, 16 diff2 -> min=2.
30: nearest: 25 diff5, 36 diff6 -> min=5.
Also for square (4) we don't need.
Pick smallest cost: 2 (pile 14). So total moves = 2. Output 2 matches.
But the note says add one candy to second pile twice: from 14 to 16 (square) which costs 2 moves. Yes.
Example 2:
n=6, all zeros. zeros are squares, so c_s=6, need n/2=3 squares, so need to convert 3 squares to non-squares. For each zero, cost_to_make_non_square = 2 (since 0 -> 2). So sum = 3*2 = 6. Output 6 matches. Note: Could we convert 0 to a non-square with 1 move? 0+1=1 (square) not good. 0+2=2 non-square, cost 2. So correct.
Example 3:
n=6, a=[120,110,23,34,25,45]
Identify squares: 25=5^2 is square; 120,110,23,34,45 are non-squares. So c_s=1, need squares=3, deficit=2. So convert 2 non-squares to squares. Compute cost_to_make_square:
120: nearest squares: 100 (diff20) or 121 (diff1) -> min=1.
110: nearest: 100 diff10, 121 diff11 -> min=10.
23: nearest: 16 diff7, 25 diff2 -> min=2.
34: nearest: 25 diff9, 36 diff2 -> min=2.
45: nearest: 36 diff9, 49 diff4 -> min=4.
Pick two smallest: 1 (120) and 2 (23 or 34). Actually we need only 2: smallest are 1 and 2. Sum=3. Output 3 matches.
But wait: is there any nuance when c_s < n/2 and some non-squares might be exactly at distance 0? No. So fine.
But we must also consider that converting a square to non-square might have cost 1 generally, but for some squares there could be a cheaper way? For example, square 1: converting to 2 costs 1. Could converting to 3 cost 2, no cheaper. Square 4: converting to 3 or 5 cost 1. Square 9: 8 or 10 cost 1. Square 16: 15 or 17 cost 1. So only 0 costs 2. So that's simple.
Thus algorithm seems straightforward: count squares, if exactly n/2, answer 0. Else if c_s > n/2, compute for each square the cost to become non-square (1 except for 0 which costs 2), sort, take smallest (c_s - n/2) of them, sum and output. Else (c_s < n/2), compute for each non-square the cost to become square (distance to nearest perfect square), sort, take smallest (n/2 - c_s), sum.
Complexities: n up to 200k, sorting costs O(n log n). That's acceptable.
But careful: "distance to nearest perfect square" for numbers up to 1e9. We need to compute it efficiently. For each a_i, we can compute floor(sqrt(a_i)) to get the square root below, and ceil sqrt? Actually compute s = floor(sqrt(a_i)). Then candidate squares: s^2 and (s+1)^2 (if (s+1)^2 might overflow? But (s+1)^2 <=? a_i <=1e9, sqrt ~31623, so (s+1)^2 <= about (31624)^2 ~ 1e9, fine. So compute diff1 = a_i - s^2, diff2 = (s+1)^2 - a_i. The min of these two is the distance to nearest square. However, if a_i is itself a perfect square, then diff1=0. That's fine. But we only compute this for non-squares in the deficit case. But we can compute anyway.
But we also need cost_to_make_non_square for squares. For a_i being a perfect square, we need cost = 0 if we keep, else cost = 1 if a_i > 0, else 2 if a_i == 0. However, is there any other case where a_i is a square but converting to non-square could be done with cost 1? For a_i > 0, yes. For a_i=0, it's 2.
But wait: Could there be a square number for which it is impossible to change to a non-square with cost 1 because both neighbors are also squares? Only 0 and maybe 1? But 1's neighbor 2 is non-square. So only 0 is problematic. So we can treat specially: if a_i == 0, cost = 2 else cost = 1.
But is there any other special case: a_i = 1? cost 1. Yes.
Thus simple.
But one more nuance: When we convert a square to non-square, we might consider converting to a non-square that is also 0? But 0 is square, so not allowed. So we must move to a non-zero non-square? Actually non-square could be any positive integer not a perfect square. So we can go to 2 from 0? That's 2 steps. Could we go to 3? cost 3, not better. So minimal is 2. So fine.
Edge Cases:
If c_s > n/2, we need to convert some squares. But what if there are insufficient squares? That can't happen because c_s > n/2, we have at least d squares to convert. So we have enough.
But what if among the squares, all are 0? Then each conversion costs 2. That's okay.
Also, could there be a scenario where we need to convert a square but that square's cost to become non-square is not 1 because maybe we cannot subtract if a_i=0? But we already accounted that.
Could there be a scenario where converting a non-square to square requires moving to a square that is 0? For a_i=2, nearest square is 1 (diff=1) or 4 (diff=2). So cost 1. That's fine.
Thus solution is clear.
But wait: The problem states that during one move they can select some pile and add one candy or remove one candy (if at least one). So we are allowed to remove candies. That means that when converting a non-square to square, we might need to remove candies to reach a lower square; that is allowed as long as we don't go below 0. However, if a_i is 0 and we need to convert to square (if 0 is already square, we wouldn't be converting from non-square). So non-square a_i > 0, so removal to lower square is allowed if we don't go negative. For instance, a_i=2, to reach 1 we need to remove 1, allowed because a_i>=1. So fine.
Now check if there is any scenario where a_i is a square but we need to convert to non-square and the minimal cost might be to remove one candy but if a_i=0 we can't remove, so we must add. So that's covered.
Thus solution is straightforward.
But I'm thinking: Could it ever be beneficial to convert a pile that is already of the deficit type (i.e., we have too many squares, but we also convert some non-squares to squares) to reduce overall cost? For example, suppose we have many squares with conversion cost 100 each, and some non-squares with conversion cost 1 each. Could we convert a non-square to square (cost 1) and then also convert a square to non-square (cost 100) so that net change in squares is 0? That doesn't help reduce the surplus; we would need to convert d squares to non-square. Adding extra pairs just increases cost. So it's never beneficial.
But consider we have c_s = 7, n/2 = 3, need to convert 4 squares to non-squares. Suppose we have 4 squares with conversion cost huge, but maybe we could convert 5 squares to non-squares (increasing cost) and also convert 1 non-square to square (cost low) to still achieve 3 squares? That would give 7-5+1=3 squares, total conversions: 5 squares->non, 1 non->square. That's 6 conversions vs 4 conversions. The sum of costs would be sum of 5 largest square conversion? Wait, we can choose which squares to convert. The optimal is to choose the 4 squares with smallest conversion cost. If those 4 are still large, but there is a non-square that can be converted to square with very small cost, could it be cheaper to instead convert more squares but with the help of cheap non-square conversion? Let's denote current squares set S, non-squares set N. We need final squares count = K = n/2. The number of squares after conversions is: |S| - x + y = K, where x = number of squares we convert to non-square, y = number of non-squares we convert to square. x and y are nonnegative integers. The total cost = sum of conversion costs for x squares + sum for y non-squares. We want to minimize total cost subject to |S| - x + y = K => y = K - |S| + x. Since K < |S|, K - |S| is negative, say d = |S| - K > 0. Then y = -d + x = x - d. For y >=0, we need x >= d. So x can be any integer >= d. Then y = x - d. Total cost = sum_{chosen x squares} cost_s + sum_{chosen y non-squares} cost_n. We need to choose which squares and which non-squares to convert. For a given x, we want to minimize the sum of smallest x costs from squares and smallest y costs from non-squares. The total cost as a function of x could potentially be lower for x > d if the additional squares we convert (the x-d extra) have very low cost and we can then also convert some non-squares that have even lower cost? Wait, but converting a non-square to square adds cost; converting an extra square to non-square adds cost. So increasing x by 1 increases total cost by (cost of the (x+1)-th cheapest square) and also increases y by 1 (since y = x - d), adding the cost of the (y)-th cheapest non-square? Actually if we increase x by 1, y also increases by 1. So the marginal cost is cost_square_{x+1} + cost_non_{y+1} (where y = x - d). Compare to staying at x = d: cost = sum of d cheapest squares (since y=0). If we go to x = d+1, cost = sum_{i=1}^{d+1} cost_square_i + sum_{j=1}^{1} cost_non_j. The change from d to d+1 is cost_square_{d+1} + cost_non_1. This could be negative? Costs are nonnegative, so it's positive. So the total cost increases. So the minimum is at x = d, y=0. So indeed we only convert squares.
But wait: could cost_non_1 be zero? No, conversion cost for non-square to square is at least 1. So definitely positive. So minimal cost achieved by only converting surplus squares.
Similarly, when c_s < n/2, we only convert non-squares.
Thus greedy approach is optimal.
Now we need to implement carefully.
Implementation Steps:
Read n, array a of size n.
Determine for each a_i whether it is a perfect square. But careful with large numbers: compute sqrt using integer sqrt function. In C++ we can use sqrt from cmath but might have precision issues; better use floor(sqrt) or custom integer sqrt: long long s = sqrt(a_i); while (ss > a_i) s--; while ((s+1)(s+1) <= a_i) s++; Actually there is std::sqrt for double, but safe to use integer sqrt: s = (int) sqrt(a_i); Then adjust: if (ss > a_i) s--; if ((s+1)(s+1) <= a_i) s++; But simpler: use sqrtl and check. Or use binary search. But given constraints, double sqrt should be fine if we do careful rounding: s = floor(sqrt(a_i) + 0.5)? Actually we need exact. Many solutions use sqrt with rounding down: long long s = sqrt(a_i); while (ss > a_i) s--; while ((s+1)(s+1) <= a_i) s++; This ensures s = floor(sqrt(a_i)). Then we can check if s*s == a_i.
But we also need cost_to_make_square for non-squares, which requires distance to nearest square. Using s, we compute diff1 = a_i - ss, diff2 = (s+1)(s+1) - a_i; min(diff1, diff2) is the cost. For a_i up to 1e9, s up to 31623, (s+1)^2 fits in 64-bit.
Also, for a_i = 0, s=0, diff1=0, diff2=1, min=0 (square).
Count squares. If count == n/2, print 0 and exit.
If count > n/2:
Let d = count - n/2.
Create vector costs.
For each a_i that is a perfect square:
if a_i == 0: cost = 2
else: cost = 1
push into costs.
Sort costs ascending.
Sum first d elements, print sum.
Else (count < n/2):
Let d = n/2 - count.
For each a_i that is not a perfect square:
compute distance to nearest square as described.
cost = that distance.
push into costs.
Sort costs ascending.
Sum first d elements, print sum.
Complexity O(n log n). n up to 200k, fine.
But is there any special case for a_i = 0 being non-square? No, 0 is square.
Now we need to ensure we correctly identify perfect squares for numbers up to 1e9. For numbers like 10^9, sqrt(10^9) ≈ 31622.7766, floor = 31622, square 31622^2 = 999950884? Actually 31623^2 = 1000004129? Let's compute: 31622^2 = (3162231622) = 3162231622 = (30000+1622)^2 = 900000000 + 2300001622= 97200000? Better: 31622^2 = 3162231622 = 31622^2. I think 31623^2 = 1000004129 > 1e9, so 31622^2 = 999950884? Actually 31622^2 = (31623-1)^2 = 31623^2 - 231623 +1 = 1000004129 -63246 +1 = 999940884? Let's compute precisely: 31623^2 = (31620+3)^2 = 31620^2 +2316203+9 = (31620^2=999824400?) This is messy but not needed. The point is we can handle using 64-bit.
But careful: (s+1)^2 may overflow 32-bit int, so use long long.
Now about the move count: The minimal moves we compute as sum of costs. That matches examples.
Now we must consider potential pitfalls: Some piles might have a_i that are perfect squares but also could become non-squares with cost 0? That would mean they are both square and non-square, impossible. So no.
Now verify with some edge cases:
n=2, a=[0,1]: both squares, count=2, n/2=1, need convert one square to non-square. Costs: 0->2 cost 2, 1->? cost 1. Smallest is 1. So answer 1. Could we achieve by converting 1 to 2 (add 1) makes non-square, other remains 0 (square). Yes, moves=1. Works.
n=2, a=[0,0]: both squares, need one non-square. Costs: each 2. So answer 2. Convert one 0 to 2 (add 2) => non-square. Moves=2. That seems minimal. Could we convert 0 to 3 (add 3) cost 3, not better. Or convert both? No.
n=2, a=[2,3]: both non-squares, count=0, need 1 square. Costs: for 2 distance to nearest square: 1 or 4 -> min=1; for 3: min=1 (to 4) or 2 (to 1) -> actually 3-1=2, 4-3=1 => 1. So both cost 1. Answer=1. Convert one of them to square: 2->1 (remove 1) or 3->4 (add 1). moves=1.
n=2, a=[2,2]: answer 1.
n=4, a=[0,1,4,9]: all squares, count=4, need 2 squares. d=2. Costs: 0->2 cost2, 1->2 cost1, 4->3 cost1, 9->8 cost1. Sorted: 1,1,1,2. Sum of two smallest = 2. Answer 2. Could we do better? Possibly convert 0 and 1: cost 3; convert 1 and 4: cost2; convert 4 and 9: cost2; minimal 2. Good.
n=4, a=[0,0,0,0]: all zeros. d=2, costs: all 2, sum=4. Could we convert one zero to 2 (cost2) and another zero to 2? But then we have two non-squares (2 and 2) and two squares (0 and 0). That works. Moves=4. Could we convert one zero to 1 (square) and another to something? That would not change count correctly. So minimal 4.
But is there a possibility to convert a zero to a non-square with 1 move? No, because 1 is square. So 2 is minimal.
Now check a scenario where some non-square could be converted to square with 0 cost? No.
Thus algorithm stands.
But one nuance: The distance to nearest square for a non-square might be computed as 0 if it's a square; but we only consider non-squares. So we can compute for all piles, but only use those where isSquare==false.
Now complexity: O(n) to compute squares and distances, then sorting for at most n elements. With n up to 200k, sorting is okay.
Potential memory: costs vector up to 200k, fine.
Now we should code. In C++:
Use vector or int (costs up to? For a_i up to 1e9, distance could be up to about 1e9? Actually max distance: For number 10^9, sqrt approx 31622, squares around 31622^2= ~ 999950884, diff to next square (31623^2) = maybe about 1e9 - 999950884 = 490... Actually compute: 31623^2 = (31623)^2 = 3162331623. 31623^2 = (31620+3)^2 = 31620^2 + 2316203 + 9 = 999,824,400? Wait, I need exact: 31622^2 = 3162231622. 3162231622 = (30000+1622)^2 = 900,000,000 + 2300001622 = 97,320,000? Actually 2300001622 = 97,320,000, plus 1622^2 = 2,630,884; sum = 900M+97.32M=997.32M plus 2.63M = 999,950,884? Let's check: 31622^2 = 31622 * 31622 = 31622 * (30000+1622) = 3162230000=948,660,000; 316221622 = 316221600=50,595,200; 3162222=695,684; sum=51,290,884; total=948,660,000+51,290,884=999,950,884. Yes. 31623^2 = (31622+1)^2 = 999,950,884 + 231622 + 1 = 999,950,884 + 63,244 + 1 = 1,000,014,129? Actually 2*31622=63,244; plus 1 = 63,245; so 999,950,884+63,245=1,000,014,129. That's > 1e9 (1,000,000,000). Wait 1,000,014,129 > 1e9. But a_i max is 1e9, so nearest square for 1e9 is 31622^2 = 999,950,884 (diff = 49,116) or 31623^2 = 1,000,014,129 (diff = 14,129). Actually 1e9 - 999,950,884 = 49,116; 1,000,014,129 - 1e9 = 14,129. So min = 14,129. So cost can be up to ~ 1e5? Actually 14k. So fits in int. But more generally, for numbers near middle of large squares, the maximum distance is about half the gap between squares. The gap between consecutive squares (k+1)^2 - k^2 = 2k+1. For k ~ 31622, gap ~ 63245. So max distance from a number to nearest square is about half of that, i.e., ~31622. So max cost is about 31623. Actually from the center, distance up to floor(gap/2) = floor((2k+1)/2) = k (approx). For k=31622, half gap ~31622.5, so max distance ~31622. So it's under 1e5. So int is fine. But for a_i=0, cost 2, also fine. So we can use int for costs. But careful: distance can be up to maybe 31623? Actually for a_i close to 0, nearest square may be 0 (if a_i is small) or 1. For a_i=2, distance 1. So all costs are small. So int safe.
Nevertheless we might use long long to avoid overflow but not needed.
Now produce code.
But before finalize, let's think about potential pitfalls:
The determination of perfect square: For large numbers, using double sqrt may give slightly incorrect integer due to floating point precision. For safety, we can compute integer sqrt via binary search or using sqrt with checks. Example: long long x = sqrt(a_i); while (xx > a_i) x--; while ((x+1)(x+1) <= a_i) x++; Then check if x*x == a_i. That's safe.
Alternatively, we can compute s = floor(sqrt(a_i)) using function like (long long) sqrt(a_i) then adjust. I'd use a function:
bool is_square(long long x) {
long long r = sqrt(x);
while (rr > x) r--;
while ((r+1)(r+1) <= x) r++;
return r*r == x;
}
But careful for x large, (r+1)*(r+1) might overflow if using int, but with long long it's fine.
Given n up to 200k, binary search per element may be heavy but acceptable? sqrt is O(1) anyway. But we can use built-in sqrt and adjust.
Another approach: precompute all squares up to 1e9? That would be about 31623 squares, could be useful but not needed.
But I'd like to write a function:
long long nearest_square_cost(long long a) {
long long r = sqrt(a);
// adjust r down
while (rr > a) r--;
while ((r+1)(r+1) <= a) r++;
long long diff1 = a - rr;
long long diff2 = (r+1)(r+1) - a;
return min(diff1, diff2);
}
But for a square, this returns 0.
But we also need to treat zero specially for cost to non-square.
But note: For a_i > 0 square, cost_to_non = 1. For a_i=0, cost_to_non = 2. That's straightforward.
But what about a_i being a perfect square but we might consider converting to non-square by moving more than 1? Could that ever be cheaper? For a_i=0, moving 1 yields 1 (square) so not good, moving 2 yields 2 (non-square) cost 2, that's minimal. So yes.
Thus algorithm done.
Let's also test some edge cases:
n=200000, all zeros. Then c_s = 200000, need d = 100000 conversions, each cost 2 => total 200000. That fits within int? 200k, fine.
n=200000, all large numbers non-squares; need to convert 100000 non-squares to squares. Sorting large array. Works.
Now potential nuance: Could there be a case where we have c_s > n/2 but there are some squares for which converting to non-square might be cheaper if we consider alternative distances? For example, a_i = 1, cost 1 to non-square. That's fine. For a_i = 0, cost 2. No other options.
But wait, what about a_i = 4? Convert to 3 cost 1, fine. So minimal cost is indeed as defined.
One more nuance: The move operation: "add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile)." So it's allowed to add arbitrarily many candies. So we can increase as needed.
Thus solution stands.
Now implement in code.
Pseudo:
#include
#include
#include
#include
using namespace std;
bool is_square(long long x) {
long long r = sqrt(x);
while (rr > x) r--;
while ((r+1)(r+1) <= x) r++;
return r*r == x;
}
long long cost_to_square(long long x) {
long long r = sqrt(x);
while (rr > x) r--;
while ((r+1)(r+1) <= x) r++;
long long diff1 = x - rr;
long long diff2 = (r+1)(r+1) - x;
return min(diff1, diff2);
}
int main() {
int n;
cin >> n;
vector a(n);
for (int i=0; i<n; ++i) cin >> a[i];
int squares = 0;
vector costs; // could be ints
for (int x : a) {
if (is_square(x)) squares++;
}
int target = n/2;
if (squares == target) {
cout << 0 << endl;
return 0;
}
if (squares > target) {
int need = squares - target; // number of squares to convert
for (int x : a) {
if (is_square(x)) {
if (x == 0) costs.push_back(2);
else costs.push_back(1);
}
}
sort(costs.begin(), costs.end());
long long ans = 0;
for (int i=0; i<need; ++i) ans += costs[i];
cout << ans << endl;
} else {
int need = target - squares;
for (int x : a) {
if (!is_square(x)) {
costs.push_back(cost_to_square(x));
}
}
sort(costs.begin(), costs.end());
long long ans = 0;
for (int i=0; i<need; ++i) ans += costs[i];
cout << ans << endl;
}
return 0;
}
But we should ensure is_square is not called twice for each element to avoid double sqrt? We can compute both in one pass. But n is only 200k, double sqrt per element is fine. However, we call is_square for each element potentially twice (first to count squares, second to process). Could compute in one pass: create arrays of bool isSq[n] and also store cost_to_sq for non-sq and cost_to_non for sq. But that's okay.
But we could improve by doing one pass: for each a_i, compute whether square and also compute conversion cost. Then count squares, and build two vectors: cost_sq_to_non for squares, cost_non_to_sq for non-squares. Then later use appropriate vector. That avoids double sqrt.
Let's design:
vector cost_sq_to_non;
vector cost_non_to_sq;
int squares = 0;
for each a:
Determine if square:
if square: squares++;
if a == 0: cost_sq_to_non.push_back(2);
else: cost_sq_to_non.push_back(1);
else: // non-square
cost_non_to_sq.push_back(cost_to_square(a));
Then proceed.
This is more efficient.
Now implement.
But careful: cost_to_square for a non-square can be computed using sqrt. We can implement a function that returns distance.
Now check large numbers: sqrt in double may have rounding error for large numbers close to squares. For example, if a = 999950884 (which is a square 31622^2), sqrt should be 31622 exactly, but double may represent it as something like 31621.999999999? Then floor becomes 31621? But then we adjust by while loops, we will correct. But we need to be careful about performance if we do while loops each time. However, the while loops could run many iterations if the initial r is far off. But with sqrt from double, r = (long long) sqrt(x) might be off by 1 at most, so the while loops will run at most a few iterations. So it's safe. Alternatively, we can use standard integer sqrt: r = sqrt(x); if (rr > x) r--; if ((r+1)(r+1) <= x) r++; Actually two if's might be enough because error at most 1. But to be robust, we can just use the while loops.
Better: Use std::sqrt from and cast to long long, then adjust as:
long long r = (long long) sqrt(x);
while (rr > x) r--;
while ((r+1)(r+1) <= x) r++;
That will correct.
But we need to be cautious about overflow of (r+1)*(r+1). Since r is at most about 31623, r+1 <= 31624, square ~ 1e9, fits in 64-bit.
Thus fine.
Alternatively, use binary search for integer sqrt for each number? That would be O(log a) per element, but 200klog(1e9) ~ 200k30=6M, also fine. But simpler with sqrt.
Now test with sample input.
We'll run mental tests.
Sample 1: n=4, a=[12,14,30,4]
For 12: not square, cost_to_square = min(|12-9|=3, |16-12|=4) =3 -> cost_non_to_sq.push_back(3)
Now we also need to think about scenario where a_i is huge (close to 1e9) and is a perfect square. For a_i >0, cost_to_non is 1. That's fine.
Now consider scenario where a_i is a perfect square but is 0? Already handled.
Now consider scenario where c_s < n/2 but some non-squares have distance to nearest square equal to 0? That would mean it's a square, but we already filtered non-squares.
Now one more nuance: The definition of "square of some integer" includes 0? Usually yes, 0=0^2. The problem statement: "Ann likes numbers which are square of some integer". Typically 0 is considered square of 0. In sample 2, they treat 0 as square because they needed to convert to non-square. So it's square.
Now finalize code.
Time complexity O(n log n).
But is there any possibility that the distance to nearest square for a non-square could be computed incorrectly for numbers like 2? Should be 1. Our method: sqrt(2)=1, r=1, while loops: 1*1=1 <=2, (r+1)^2=4 >2, so r stays 1. diff1=2-1=1, diff2=4-2=2, min=1. Good.
For number 3: sqrt(3)=1, r=1, diff1=2, diff2=1 -> min=1. Good.
For number 0: sqrt(0)=0, r=0, diff1=0, diff2=1 -> min=0 -> square.
For number 1: sqrt(1)=1, r=1 (since sqrt gives 1 exactly), while loops: 1*1=1 <=1, (2)^2=4>1, r=1. diff1=0, diff2=3 -> min=0 -> square.
Now for number like 999950884 (square 31622^2): sqrt yields maybe 31621.999..., r cast to 31621? Then while (rr > x) will reduce? Actually r=31621, rr? 31621^2 =? likely less than x? Actually need compute: If sqrt returns slightly less than 31622, floor yields 31621. Then 31621^2 is (31622-1)^2 = 31622^2 - 231622 +1 = 999950884 - 63244 +1 = 999887641? That's less than x, so rr <= x. Then the second while: while ((r+1)*(r+1) <= x) will increase r: (31622)^2 = 999950884 <= x, so r becomes 31622. Then it's correct.
If sqrt returns slightly more than 31622, r could be 31622, rr > x? 31622^2 = 999950884, equal? Actually 31622^2 = 999950884 exactly, so if sqrt returns exactly 31622, r=31622, rr = x, so no adjustment needed. If sqrt returns 31622.0001, r=31622, rr =? Actually (long long) cast truncates, so still 31622, rr = x. So fine.
Thus function works.
Now we need to be careful about large number of squares case: we compute cost_sq_to_non for each square. For squares >0, cost is 1. For 0, cost 2. So that's easy.
Now ensure we handle large input fast: Use scanf/printf or cin with ios_base sync.
Now edge case: n=200000, all squares, all >0 except maybe some zeros. Sorting of costs (all 1's except zeros maybe). Sorting O(n log n). That's okay.
Now let's also test some random case manually to double-check reasoning.
Suppose n=2, a=[2,2]. We determined answer 1. Our algorithm: squares=0, target=1, need=1. For each non-square (both), cost_to_square = min(|2-1|=1, |4-2|=2)=1. So costs [1,1], need=1 => sum=1. Works.
Suppose n=2, a=[10,10]: nearest: 9 diff1, 16 diff6 => cost=1. So always 1? Actually many numbers have cost 1, but some have cost >1? Let's see 2: cost1, 3:1, 5:1, 6:1? 6 to 4 diff2, to 9 diff3 -> cost2? Actually 6: 4 diff2, 9 diff3 -> cost2. So some numbers have cost 2. 6 cost2. 7: to 9 diff2, to 4 diff3 => cost2. 8: to 9 diff1, cost1. 10: to 9 diff1, cost1. 11: to 9 diff2, to 16 diff5 -> cost2. 12: to 9 diff3, to 16 diff4 -> cost3? Actually 12 to 9 diff3, to 16 diff4 => cost3. So some numbers have cost up to maybe ~31622. So our algorithm picks the smallest ones.
Now suppose n=4, a=[6,6,6,6]. All non-squares, squares=0, target=2, need=2. Costs: each 6 -> cost2. Sorted: [2,2,2,2], sum=4. Could we do better by converting some squares? There are no squares. So answer 4. But is it possible to achieve with fewer moves? Let's try alternative: Change two piles to squares: 6->4 (remove 2) cost2 each, total 4. Could we change one pile to square and another to non-square? Wait, we need exactly 2 squares, 2 non-squares. So we need to convert two piles to squares. Could we convert one pile to square with cost less than 2? For 6, the nearest square is 4 (cost2) or 9 (cost3). So min cost 2. So total 4. So answer 4. So algorithm correct.
Now suppose n=4, a=[6,8,10,15]. Squares? none. Need 2 squares. Costs: 6->4 (2) or 9 (3) =>2; 8->9 (1) =>1; 10->9 (1) =>1; 15->16 (1) =>1. So costs [2,1,1,1]. Two smallest: 1+1=2. Answer 2. Could we achieve with 2 moves? e.g., change 8 to 9 (+1) and 10 to 9 (+1) -> squares: 9,9; non-squares:6,15. That's valid? 6 non-square, 15 non-square. Yes, moves=2. So fine.
Now consider a case with squares surplus: n=4, a=[0,1,2,3]. squares: 0 and 1 are squares => c_s=2, target=2 => already satisfied? Actually c_s=2 equals target, so answer 0. Indeed condition already satisfied: 2 squares (0 and1), 2 non-squares (2 and3). So output 0. Good.
Now if n=4, a=[0,1,4,5]: squares:0,1,4 -> c_s=3, target=2, need to convert 1 square to non-square. Costs for squares: 0->2 cost2, 1->2 cost1, 4->3 cost1. Sorted: [1,1,2]; need=1 => pick 1. Answer 1. Could we convert 1 to 2 (add1) -> squares:0,4; non-squares:2,5. moves=1. Yes.
Now if there is a zero among squares, cost 2 may be selected if it's among the smallest. But if we have many squares, we might avoid converting zeros if there are cheaper ones. So algorithm picks cheapest.
Now think about potential overflow or performance: Sorting 200k ints is fine.
Now one more nuance: When c_s > n/2, the cost to convert a square to non-square we set as 1 for all positive squares. But is there any scenario where a positive square might have a cheaper conversion by moving more than 1? Obviously not, because 1 is minimal move count. So it's correct.
But wait: Could there be a scenario where a positive square is 1? cost 1; 4 cost1; etc. So all positive squares have cost 1, zeros cost 2. So essentially the costs vector for squares is composed of many 1s and some 2s. So the minimal sum for converting d squares is: as many 1s as possible, then 2s. So we could compute without sorting by counting number of positive squares and zeros. Because the costs are only 1 or 2. So we can compute the answer in O(n) without sorting for that case. However, for non-squares, costs vary, so sorting needed. But we can also apply counting sort since maximum cost is maybe ~31623? Actually maximum distance to nearest square for numbers up to 1e9 is about 31623 (as argued). Let's confirm: For a number in between k^2 and (k+1)^2, the maximum distance to nearest square is floor( ( (k+1)^2 - k^2 ) / 2 ) = floor( (2k+1)/2 ) = k (when the number is exactly halfway? But half way would be k^2 + (2k+1)/2 = k^2 + k + 0.5, distance to either square = k+0.5? Actually distance to k^2 = k + 0.5, to (k+1)^2 = k+0.5, but since integers, the maximum min distance is ceil? For integer a, the maximum min distance is ceil( (gap)/2 )? Let's compute: gap = (k+1)^2 - k^2 = 2k+1. The integer that minimizes the max distance is at the midpoint, but min distance to either square for integer a: The worst-case min distance is floor(gap/2) maybe? Example: k=1, squares 1 and 4, gap=3. Numbers: 2 (distances: 1,2) -> min=1; 3 (distances:2,1) -> min=1; so max min distance =1 = floor(3/2)=1. For k=2, squares 4 and 9, gap=5. Numbers: 6 (distances:2,3) min=2; 7 (3,2) min=2; 5 (1,4) min=1; 8 (4,1) min=1. Max min=2 = floor(5/2)=2. For k=3, squares 9 and 16, gap=7. Max min distance =3? Check 12: dist 3 to 9, 4 to 16 => min=3; 13: 4,3 => min=3; So max=3 = floor(7/2)=3. So indeed max min distance = floor((2k+1)/2) = k. The largest k is floor(sqrt(1e9)) ≈ 31622, so max min distance ≈ 31622. So cost_to_square is at most about 31622. So the costs for non-squares are bounded by ~31623. So we could use counting sort with array of size 31623+1, which is small, making O(n) possible for that branch too. But n=200k, sorting O(n log n) is fine. However, we may want to be careful with the square branch: we can avoid sorting by simply counting number of zeros among squares, because costs are only 1 or 2. So for that branch, we can compute need = c_s - n/2. Let cnt_pos_sq = number of squares with a_i > 0; cnt_zero_sq = number of squares with a_i == 0. Then we first use as many positive squares (cost 1) as possible: if need <= cnt_pos_sq, answer = need * 1; else answer = cnt_pos_sq * 1 + (need - cnt_pos_sq) * 2. But we must also consider that we cannot exceed cnt_zero_sq. Since total squares = cnt_pos_sq + cnt_zero_sq, and need <= c_s, so if need > cnt_pos_sq, the remaining need must be taken from zeros, cost 2 each. So answer = min(need, cnt_pos_sq)*1 + max(0, need-cnt_pos_sq)*2.
But is it always optimal to convert positive squares before zeros? Yes, because cost 1 < 2, so we want to convert cheapest first. So we can compute directly without sorting.
Similarly, for the non-square branch, we could sort, but we could also bucket sort due to limited range. Since maximum cost ~ 31623, we could count frequencies of each cost using an array of size maybe 31623+5. But careful: cost could be 0? For non-squares, cost is at least 1. So we could use an array of size up to maybe 31623 (or 1e5). That is efficient. But sorting is also okay, but given n=200k and cost values up to 31623, counting sort might be faster. However, for simplicity, sorting is fine. But there is nuance: For non-square numbers, the cost is the distance to nearest square, which might be as high as about 31623, but if we compute via sqrt and min, we get integer. Sorting 200k integers is very fast in C++ (quicksort). So I'd stick with sorting.
But the problem statement says n up to 200,000, which is fine.
Now the algorithm is ready.
Potential issues: Memory usage: vector costs for non-squares can be up to 200k, fine.
Now we need to consider if a_i can be 0 and non-square? No, 0 is square.
Thus code should pass.
Now produce final solution in C++.
But before final, let's test some tricky edge cases.
Edge case 1: n=2, a=[0,2]. Squares:0 only -> c_s=1, target=1 => answer 0? Actually condition: exactly n/2 =1 square, and 1 non-square. We have one square (0) and one non-square (2). So condition already satisfied -> answer 0. Our algorithm: squares = 1, target=1, output 0. Good.
Edge case 2: n=2, a=[0,1]. Both squares, need 1 conversion. As earlier, answer 1.
Edge case 3: n=2, a=[1,2]. squares:1 is square -> c_s=1, target=1, already satisfied? Yes, 1 square, 1 non-square (2). So answer 0. Good.
Edge case 4: n=2, a=[2,3]. squares=0, need 1. costs 1 each, answer 1.
Now consider large numbers: a_i = 1e9 = 1000000000. Determine if square? 31622^2=999950884, 31623^2=1000014129? Actually we computed earlier 31623^2 = 1,000,014,129 > 1e9, so 1e9 is not square. cost: to 31622^2 = 1000000000-999950884 = 49116; to 31623^2 = 1000014129-1000000000=14129? Wait, recalc 31623^2: 31623 * 31623. Let's compute precisely: 31623^2 = (31620+3)^2 = 31620^2 + 2316203 + 9. 31620^2 = (3162*10)^2 = 3162^2 100? Actually easier: 31623^2 = 3162331623. Let's do exact: 31623 * 31623:
31623 * 30000 = 948,690,000
31623 * 1000 = 31,623,000 -> total 980,313,000
31623 * 600 = 18,973,800 -> total 999,286,800
31623 * 20 = 632,460 -> total 999,919,260
31623 * 3 = 94,869 -> total 1,000,014,129
Yes, 1,000,014,129. So diff to 1e9 = 14,129. The other square 31622^2 we computed as 999,950,884, diff = 49,116. So min cost = 14,129. So for non-square, costs can be in thousands. Sorting okay.
Now test with n=200000, all numbers = 6 (cost 2). Then we need 100000 conversions, each cost 2 => total 200000. Sorting 200k ints is trivial.
Now potential pitfalls: The function is_square might be slow if we use while loops for each number, but at most a couple iterations. Acceptable.
But we should be careful to avoid repeated sqrt for the same number if we compute both is_square and cost_to_square separately. We'll implement in one pass as described.
Now implementation details in C++:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector a(n);
for (int i=0; i<n; ++i) cin >> a[i];
int squares = 0;
vector costNonToSq;
int pos_squares = 0, zero_squares = 0; // for squares case
for (int x : a) {
// compute integer sqrt and determine square
ll r = sqrt(x);
while (rr > (ll)x) r--;
while ((r+1)(r+1) <= (ll)x) r++;
if (rr == x) {
squares++;
if (x == 0) zero_squares++;
else pos_squares++;
} else {
// non-square, compute cost to nearest square
ll diff1 = x - rr;
ll diff2 = (r+1)*(r+1) - x;
int cost = min(diff1, diff2);
costNonToSq.push_back(cost);
}
}
int target = n/2;
if (squares == target) {
cout << "0\n";
return 0;
}
if (squares > target) {
int need = squares - target;
// we have pos_squares (cost 1) and zero_squares (cost 2)
ll ans = 0;
// use as many pos_squares as possible
int use_pos = min(need, pos_squares);
ans += use_pos * 1;
need -= use_pos;
// remaining from zero_squares
ans += need * 2; // need <= zero_squares because total squares = pos+zero >= target+need
cout << ans << "\n";
} else {
int need = target - squares;
sort(costNonToSq.begin(), costNonToSq.end());
ll ans = 0;
for (int i=0; i<need; ++i) ans += costNonToSq[i];
cout << ans << "\n";
}
return 0;
}
But wait: In the squares > target branch, we used pos_squares and zero_squares counts. However, careful: Are we sure that all positive squares have cost exactly 1? Yes, as argued. But what about square 1? cost 1; square 4 cost 1; etc. So fine.
But is there any possibility that a positive square could be converted to non-square with cost 0? No.
Thus the branch is fine.
But note: In our one-pass, we didn't build costSqToNon vector; we just counted pos and zero squares. That works because costs are uniform. However, we must ensure that we count correctly: For each square, if x > 0, it's pos_squares++; else zero_squares++. Yes.
But we have to be careful: For squares, we also need to consider that if we need to convert a square to non-square, we may need to choose which squares to convert. Since all positive squares cost 1, and zeros cost 2, the optimal is to convert positive squares first. So we simply compute answer as above.
But is there any scenario where converting a zero might be cheaper than converting a positive square? No.
Thus answer can be computed without sorting.
Now for non-squares branch, we need costNonToSq. But we also might consider that some non-squares could have cost 0? No, because they are not squares. So cost at least 1.
Now test with sample 2: all zeros, squares=6, pos_squares=0? Actually zeros are squares, x==0, so zero_squares=6, pos_squares=0. target=3, need=3. use_pos = min(3,0)=0; ans=0; need=3; ans+=3*2=6. Correct.
Sample 1: squares: only 4 is square, pos_squares=1, zero_squares=0. target=2, squares=1 < target, so we go to non-squares branch. costNonToSq from non-squares: [3,2,5] sorted -> sum of first 1? Actually need = 1? Wait squares=1, target=2, need=1. Yes sum of first smallest = 2. Good.
Now sample 4: squares=5, pos_squares count: which squares? 121,81,100,1,0 -> pos_squares=4 (121,81,100,1), zero_squares=1 (0). target=5, squares=5 => output 0. Good.
Edge case: Suppose we have squares > target and there are some positive squares and some zeros. Need to convert e.g., need=3, pos_squares=2, zero_squares=2. Then ans = 21 + 12 = 4. That's minimal.
Thus code works.
Now we need to ensure we include needed headers and using namespace std.
Now also note: The variable type for r: long long (or unsigned long long). But x is up to 1e9, r is up to 31623, so int would be fine. But to avoid overflow when computing (r+1)*(r+1) we should use long long to be safe. So use long long for r.
Now implement.
But careful: In the loop, we compute r = sqrt(x). sqrt returns double. If x is integer up to 1e9, sqrt returns double. Casting to long long truncates. Then we adjust. That's fine.
But some compilers may have sqrt ambiguous, but using std::sqrt is fine.
Alternatively, we could use int r = sqrt(x); but then (r+1)*(r+1) might overflow if r is int and product exceeds 2^31-1. For r ~ 31623, (r+1)^2 ~ 1e9, which is within 32-bit signed int range (max ~2.147e9). So it's safe. But to be safe, use long long.
Now there is also a nuance: When x is 0, r = sqrt(0)=0, loops fine.
Now we also need to compute cost for non-square using diff1 and diff2. Ensure we cast to long long for the differences. But x and r are integer, diff1 = x - rr; rr is within range; all good.
Now what about large x? It's fine.
Now testing on random generated data to be thorough.
We'll also consider if there is any scenario where a_i is a perfect square but we might want to convert it to non-square via moving to a non-square that is closer than 1? Not possible.
Now note: In the squares > target case, we used pos_squares and zero_squares. But suppose there are squares that are >0 but maybe we could convert to non-square with cost 0? Not possible. So it's fine.
But what about squares that are 1? The minimal non-square is 2, cost 1. Good.
Now any square >0 indeed has at least one neighbor non-square. However, consider square 1: neighbor 2 is non-square, cost 1; neighbor 0 is square. So yes.
Now the problem statement says: "During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile)." So moves are per candy change. So cost as computed.
Thus final solution.
Now we can write final answer.
But before finalize, we might also consider if it's possible to achieve the condition with fewer moves by changing multiple piles? The greedy approach is correct as proven earlier.
Now we should consider if there is any possibility that a non-square could be changed to a non-square with zero moves? That's not a conversion.
Now the answer will be within 64-bit? Max moves: n/2 * max cost. n/2=100k, max cost ~31622, product ~3.16e9, which fits in 32-bit signed? 3.16e9 > 2.147e9 (2^31-1). So it could exceed 2^31. Indeed 100k * 31622 = 3,162,200,000 > 2,147,483,647. So we need 64-bit (long long) for answer. In our code we used ll ans, that's fine.
But also costNonToSq might be up to 31622, but we sum up to 100k of them, so total could be >2^31. So we should use long long for ans.
Now in the squares branch, ans = use_pos * 1 + need * 2. use_pos up to 100k, need up to 100k, so max ans = 100k * 2 = 200k, which fits in int. But it's okay to use long long.
Now we should also consider the case where we need to convert squares, but we have pos_squares enough? Since need <= squares = pos+zero, if need > pos, we take from zeros, as we did.
Now we should also check that in the non-squares branch, we have enough costs: need <= number of non-squares? Because squares + non = n, need = target - squares = n/2 - squares. Since squares < target, n/2 - squares > 0. The number of non-squares = n - squares. Is n - squares >= need? need = n/2 - squares, so n - squares = n/2 + (n/2 - squares) = n/2 + need, so yes at least need. So we have enough.
Now we should ensure that we don't accidentally use elements beyond the vector size. We'll sort and then sum first need.
Now we must also consider that for non-squares, cost might be 0? No.
Now I think it's correct.
Let's test more with random small n via brute force? Not needed but we can reason.
Now we should also think about the time: using sqrt for each element is fine.
Now we can produce final code.
But wait: There is a nuance: In the squares > target branch, we used pos_squares and zero_squares. However, what if there are squares that are 0? Already accounted. But what about squares that are 1? They are positive, cost 1. So correct.
Now also consider the possibility that a_i is a perfect square but we might want to convert it to non-square by removing all candies to 0? That would be 1 move? Actually if a_i=1, removing one candy yields 0, which is square, not non-square. So not good. If a_i=4, removing one yields 3 (non-square) cost 1. So fine.
Now there is a nuance: Could we convert a square to a non-square by adding zero candies? That is not a move.
Thus all good.
Now final code.
But also we could further optimize non-squares branch by using counting sort if we want to guarantee O(n). But not necessary.
Let's implement final solution.
One more thing: Use of sqrt from cmath: for large numbers, sqrt might be a bit slow but fine.
Alternatively, we can compute integer square root via built-in function like int(sqrt(x)), but we adjust. I'll implement as described.
Now final code:
code
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int squares = 0;
int pos_squares = 0, zero_squares = 0;
vector<int> costNonToSq;
costNonToSq.reserve(n); // at most n
for (int x : a) {
ll r = sqrt(x);
// adjust r to floor sqrt
while (r * r > x) --r;
while ((r + 1) * (r + 1) <= x) ++r;
if (r * r == x) {
++squares;
if (x == 0) ++zero_squares;
else ++pos_squares;
} else {
ll diff1 = x - r * r;
ll diff2 = (r + 1) * (r + 1) - x;
int cost = min(diff1, diff2);
costNonToSq.push_back(cost);
}
}
int target = n / 2;
if (squares == target) {
cout << "0\n";
return 0;
}
if (squares > target) {
int need = squares - target;
ll ans = 0;
int use_pos = min(need, pos_squares);
ans += use_pos * 1LL;
need -= use_pos;
ans += need * 2LL;
cout << ans << "\n";
} else {
int need = target - squares;
sort(costNonToSq.begin(), costNonToSq.end());
ll ans = 0;
for (int i = 0; i < need; ++i) {
ans += costNonToSq[i];
}
cout << ans << "\n";
}
return 0;
}
But double-check: In the squares branch, we assume that converting a positive square costs exactly 1, but is that always true? Consider square 1: to become non-square, we can go to 2 (add 1). So cost 1. Square 4: to 3 or 5, cost 1. Square 9: to 8 or 10, cost 1. So yes.
But what about square numbers that are extremely large like 10^9? But 10^9 is not square. For square like 31622^2 = 999950884, both neighbors 999950883 and 999950885 are not squares, so cost 1. So all positive squares have cost 1.
Thus fine.
Now we might also consider the possibility that a_i is a perfect square and equals something like 1, but we could convert to non-square by removing all candies to 0? That yields 0 which is square, not non-square. So not good. So cost 1.
Now everything is good.
But wait: In the squares > target branch, we used only counts. But what about if there are squares that are positive but the cost might be 0 if we could convert to non-square without moves? That's impossible.
Thus answer.
Now possible optimization: For non-squares, we might compute cost without sqrt using precomputed squares? Not needed.
Now the problem statement includes example: Input 6: 0 0 0 0 0 0 => output 6. We match.
Thus final answer.
But there is also a nuance: In some programming languages, sqrt for large numbers may have precision issues that cause r to be off by more than 1? Actually double has 53 bits of mantissa, which can represent integers up to 2^53 exactly (~9e15). So for numbers up to 1e9, double can represent them exactly. sqrt of an integer may not be exact, but the rounding error is small; taking floor may give correct floor or off by 1. So we adjust with while loops, which will fix.
Alternatively, we could compute integer sqrt via:
int r = sqrt(x + 0.5); // rounding to nearest, but might still be off for perfect squares? Better to use the while method.
I'll keep while loops.
Now test with edge x=0: r = sqrt(0)=0, loops fine. For x=1: sqrt(1)=1, loops not needed.
Now test with x=2: sqrt(2) ≈1.414, r=1; r*r=1 <=2, while (r+1)^2 =4 >2, so r stays 1; correct floor.
Now test with x=3: similar.
Now test with x=4: sqrt(4)=2, r=2; r*r=4 <=4; while (r+1)^2=9>4; ok.
Now test with x=999950884 (square). sqrt(999950884) might be exactly 31622 if computed precisely? Possibly. But if not, loops adjust.
Thus correct.
Now we should also note that for non-square numbers, we compute cost as min(diff1,diff2). Since we have floor sqrt r, the nearest square is either r^2 or (r+1)^2. This is true because if a_i is not a perfect square, it lies between r^2 and (r+1)^2, exclusive. So the nearest square is indeed one of those. So cost computed is correct.
Now finalize.
But wait: The problem says n is even and 2 ≤ n ≤ 200000. So fine.
Now the solution seems correct.
But before final answer, let's double-check reasoning for squares > n/2 case with the following: suppose we have a mix of zeros and positive squares. The greedy picks positives first because cost 1. Is there any scenario where converting a zero might be cheaper because we could convert zero to 2 (cost 2) but maybe converting a positive square to non-square requires more than 1? No, it's exactly 1. So positive squares are cheaper.
Thus answer.
Now we can also consider the possibility of converting a positive square to non-square by removing candies to 0, which would cost (square) steps, but that's not minimal; we would always prefer neighbor.
Thus everything fine.
Now we should output the answer as integer.
Now produce final answer.
But I recall that in some Codeforces problems, there might be a twist: The definition of "square of some integer" includes 0? Yes, as per sample 2. So correct.
Now we should also think about scenario where a_i is very large and exactly a square, but maybe its neighbors are also squares? As argued impossible except 0 and 1? Actually 0 and 1 are consecutive squares, but 0 and 1 are both squares. For 1, neighbor 0 is square, neighbor 2 is not. So only 0 is special. So positive squares always have neighbor non-square.
Thus fine.
Now we can finalize the solution.
But wait: In the squares > target branch, we used pos_squares and zero_squares. However, could there be squares that are 0 but we can convert to non-square with cost 1? No, because 0 -> 1 (square) only. So cost 2.
Thus correct.
Now I think it's good.
Now deliver final answer.
One more test: n=200000, all a_i = 0 => squares=200000, target=100000, need=100000. pos_squares=0, zero_squares=200000, ans=100000*2=200000. Works.
Now also test n=200000, all a_i = 1 => squares=200000, pos_squares=200000, ans=100000*1=100000.
Now test n=200000, half zeros and half ones: squares=200000? Actually both 0 and 1 are squares, so all squares, squares=200000, need=100000. pos_squares: ones count maybe 100000, zero count 100000. Then use_pos = min(100000, 100000)=100000, ans=100000, remaining need=0. So answer 100000. But is that optimal? Convert each 1 to 2? Actually 1 -> 2 (add 1) cost 1 each. So total 100000. Good.
Now test n=200000, all a_i = 2: squares=0, target=100000, need=100000. For each 2, cost = 1 (to 1) or 2 (to 4) -> min=1. So ans=100000. Sorting of 200000 ones is trivial.
Now check extreme: n=200000, all a_i = 6: cost 2 each, need 100000 => ans=200000.
Now check a mix: All non-squares but with varying costs. Sorting works.
Thus final.
Now one more nuance: In the non-squares branch, we push cost for each non-square. But what if need is zero? Not possible because squares < target => need >0. But if squares == target, we already output 0, so non-squares branch only when need >0.
Thus safe.
Now code is ready.
But wait: In the squares branch, we compute need = squares - target. But what if need is negative? That's not possible because squares > target. So fine.
Now we should also consider if the squares branch can be applied when squares > target but pos_squares and zero_squares are correctly counted. Yes.
Now just to be thorough, maybe there is a scenario where a positive square could have a cost to become non-square of 0? That would be if the square itself is also a non-square? Impossible.
Now finalize.
But I recall an earlier Codeforces problem "Squares and not squares" or something similar. The solution is exactly as described.
Now implement and final answer.
One more note: In C++, using vector a(n) and reading with cin is fine after syncing.
Now let's think about the time for the sqrt loops: The while loops might run a couple iterations, but for worst-case, if sqrt is off by a lot? No, due to double precision, it's off by at most 1 or 2. So it's fine.
But there is a slight risk: for x very close to a square, sqrt may return something like 31622.0000000001, then r = 31622, r*r = 999950884? Actually if x is a perfect square, sqrt should be exact in double if the integer is representable? For integers up to 1e9, double can represent them exactly, but sqrt may not be exact. However, the sqrt of a perfect square integer may not be computed exactly due to rounding errors; for example, sqrt(4) is exactly 2.0, but sqrt(25) maybe 5.0 exactly? Actually sqrt of perfect squares that are not too large often are exact because sqrt is a rational number? Not exactly; sqrt of an integer that is a perfect square is an integer, and floating point representation may not be able to represent the result exactly if it's not a power of two? Actually sqrt(25) = 5.0 exactly because 5.0 is exactly representable. In IEEE double, integers up to 2^53 are exactly representable, so 5 is exact. The sqrt function returns a double that may be exactly 5.0 if the algorithm computes correctly. So it's generally safe. However, to be robust, the while loops are there.
Thus we are good.
Now we can produce final answer.
But we need to output minimal number of moves.
Now final code:
code
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int squares = 0;
int pos_squares = 0, zero_squares = 0;
vector<int> costs_non;
for (int x : a) {
long long r = sqrt(x);
while (r * r > x) --r;
while ((r + 1) * (r + 1) <= x) ++r;
if (r * r == x) {
++squares;
if (x == 0) ++zero_squares;
else ++pos_squares;
} else {
long long diff1 = x - r * r;
long long diff2 = (r + 1) * (r + 1) - x;
costs_non.push_back(min(diff1, diff2));
}
}
int target = n / 2;
if (squares == target) {
cout << 0 << '\n';
return 0;
}
if (squares > target) {
int need = squares - target;
long long ans = 0;
int use_pos = min(need, pos_squares);
ans += use_pos;
need -= use_pos;
ans += need * 2;
cout << ans << '\n';
} else {
int need = target - squares;
sort(costs_non.begin(), costs_non.end());
long long ans = 0;
for (int i = 0; i < need; ++i) {
ans += costs_non[i];
}
cout << ans << '\n';
}
return 0;
}
Now confirm with sample.
Sample 1: Already tested.
Now minor: In the squares branch, we use ans += use_pos; that is fine (use_pos is int, ans is long long). Good.
Now final answer.
But before final, double-check for potential integer overflow in computing (r+1)*(r+1) when r is long long and x up to 1e9; r max ~31623, (r+1)^2 max ~ (31624)^2 = 1,000,014,176 < 2^31? Actually 1,000,014,176 > 2^31-1 (2,147,483,647) still less than 2^31? Wait 2^31-1 = 2,147,483,647, so it's fine. But using long long is safe.
Now I think it's good.
Now I'd like to provide the final answer.
But the problem statement might have a twist: The numbers can be up to 10^9, but we also have to consider that the piles can be made to have any number of candies (including zero) after operations. So our approach works.
Thus final answer as above.
Now I will produce the final solution. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
int squares = 0, pos_squares = 0, zero_squares = 0;
vector<int> cost_non; // conversion cost for non‑squares
for (int x : a) {
// integer square root floor r
ll r = sqrt(x);
while (r * r > x) --r;
while ((r + 1) * (r + 1) <= x) ++r;
if (r * r == x) { // x is a perfect square
++squares;
if (x == 0) ++zero_squares;
else ++pos_squares;
} else { // x is not a square
ll diff1 = x - r * r;
ll diff2 = (r + 1) * (r + 1) - x;
cost_non.push_back(min(diff1, diff2));
}
}
int target = n / 2;
if (squares == target) {
cout << "0\n";
return 0;
}
if (squares > target) {
int need = squares - target; // how many squares to change
ll ans = 0;
int use_pos = min(need, pos_squares); // cheap ones (cost 1)
ans += use_pos;
need -= use_pos;
ans += need * 2; // remaining are zeros (cost 2)
cout << ans << '\n';
} else {
int need = target - squares; // how many non‑squares to change
sort(cost_non.begin(), cost_non.end());
ll ans = 0;
for (int i = 0; i < need; ++i) ans += cost_non[i];
cout << ans << '\n';
}
return 0;