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.
n个数字(n为偶数),要求你将其中一半的数置为平方数,另一半置为非平方数。
你允许对任意一个数字加减,要求你加减的总和最小并输出这个值。
对于每个数字进行操作,计算其距离最近的平方数的差值,剔除差值为0的数字,然后对差值进行排序。
一般来说,如果平方数的数量少了,直接加入排序中较小的数字,平方数多了,则加1使其不为平方数,但要注意的是,如果初始为0,则要加2.
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<stack> #include<map> #include<vector> #include<queue> using namespace std; const int MAXN=1e6+10; const double eps=1e-4; const int INF=1<<30; const int mod=1e9+7; #define ll long long #define edl putchar(' ') #define useit ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define FOR(i,a,b) for(int i=a;i<=b;i++) #define ROF(i,a,b) for(int i=a;i>=b;i--) #define mst(a) memset(a,0,sizeof(a)) #define mstn(a,n) memset(a,n,sizeof(a)) #define zero(x)(((x)>0?(x):-(x))<eps) int n,m,k=0,a[MAXN+10],l,c0=0; int main() { scanf("%d",&n); k=n; m=n/2; FOR(i,1,n) { scanf("%d",&l); double k=sqrt(l); a[i]=min(ceil(k)*ceil(k)-l,l-floor(k)*floor(k)); if(a[i]==0) i--,n--,m--; if(l==0) c0++; } sort(a+1,a+n+1); ll ans=0; if(m<0) { m=-m; if(c0>k/2) ans+=2*(c0-k/2); else ans+=m; } else { FOR(i,1,m) ans+=a[i]; } cout<<ans<<endl; }