Amr and Chemistry CodeForces - 558C

Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.

Amr has n different types of chemicals. Each chemical i has an initial volume of ailiters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.

To do this, Amr can do two different kind of operations.

  • Choose some chemical i and double its current volume so the new volume will be 2ai
  • Choose some chemical i and divide its volume by two (integer division) so the new volume will be 

Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?

Input

The first line contains one number n (1 ≤ n ≤ 105), the number of chemicals.

The second line contains n space separated integers ai (1 ≤ ai ≤ 105), representing the initial volume of the i-th chemical in liters.

Output

Output one integer the minimum number of operations required to make all the chemicals volumes equal.

Examples

Input

3
4 8 2

Output

2

Input

3
3 5 6

Output

5

Note

In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.

In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.

题意:给你n个数,每次操作可以使其中一个数*2或/2(向下取整),问最少几次操作使得这n个数相同。

思路:处理每个数,看看每个数都能够到达什么状态,然后用book[i]记录能够到达i的数有几个,ans[i]记录能够到达i的数到达i这个数需要多少步。

注意:如果一个数是奇数,那么它本身一直乘二所能到达的数字,和它除2向下取整再一直乘二所能到达的数字是完全不相同的。因为在二进制下除二后相当于左移把末尾的1弄没了,以后再右移时前缀都不一样了。所以在向下除的过程中每次遇到奇数都要处理一下。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int a[100009],book[200009],ans[200009],n,maxx,minn;//book表示能够到达i这个数的数量,ans表示所有数到达i所需的次数 
const int inf=1<<29;
void solve(int x)
{
	int num=x;
	int step=0;
	book[x]++;
	while(num<=maxx)
	{
		num*=2;
		step++;
		book[num]++;
		ans[num]+=step;
	}
	num=x;
	step=0;
	while(num)
	{
		if(num%2&&num!=1)
		{
			num/=2;
			step++;
			book[num]++;
			ans[num]+=step;
			int num1=num;
			int step1=step;
			while(num1<=maxx)
			{		
				num1*=2;
				step1++;
				book[num1]++;
				ans[num1]+=step1;
			}
		}
		else
		{
			num/=2;
			step++;
			book[num]++;
			ans[num]+=step;
		}
	}
}
int main()
{
	scanf("%d",&n);
	maxx=-1;minn=inf;
	memset(book,0,sizeof(book));
	memset(ans,0,sizeof(ans));
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		maxx=max(a[i],maxx);
	}
	for(int i=1;i<=n;i++)
		solve(a[i]);
	for(int i=1;i<=2*maxx;i++)
		if(book[i]==n)
			minn=min(minn,ans[i]);
	printf("%d\n",minn);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/88124166