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.
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 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.
4 12 14 30 4
2
6 0 0 0 0 0 0
6
6 120 110 23 34 25 45
3
10 121 56 78 81 45 100 1 0 54 78
0
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.
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200010;
int a[maxn];
vector<int>g;
int main(){
int n;
scanf("%d", &n);
int cnt = 0, x;
for(int i = 1; i <= n; ++i){
scanf("%d", &a[i]);
x = sqrt(a[i]);
if(x * x == a[i]) cnt++;
}
if(cnt == n / 2) cout<<0<<endl;
else if(cnt < n / 2){
for(int i = 1; i <= n; ++i){
x = sqrt(a[i]);
if(x * x != a[i]){
g.push_back(min(a[i] - x * x, (x + 1) * (x + 1) - a[i]));
}
}
sort(g.begin(), g.end());
long long ans = 0;
for(int i = 1; i <= n / 2 - cnt; ++i){
ans += g[i - 1];
}
cout<<ans<<endl;
}
else{
int ling = 0, ans;
for(int i = 1; i <= n; ++i){
if(a[i] == 0) ling++;
}
if(cnt - ling >= cnt - n / 2) cout<<(cnt - n / 2)<<endl;
else{
ans = cnt - ling;
ans += (cnt - n / 2 - ans) * 2;
cout<<ans<<endl;
}
}
}
/*
题意:
2e5个数,每个数每次可以加1或者减1,保证每个数是非负的,问最少需要操作多少次,可以让所有
数的一半是平方数,一半不是。
思路:
如果已经满足要求输出0,如果不满足分类讨论一下。
首先贪心一个结论,无论怎么操作,非平方数和平方数的个数变化是单调的。那么如果平方数少,
那么就把每个数变成平方数的次数排序然后统计一下。如果非平方数少,那么加1即可,0特判一下。
*/