C. Amr and Chemistry(Codeforces Round #312(div2))

C. Amr and Chemistry
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 ai liters. 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.

Sample test(s)
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.


题目大意:

      通过对数组里的元素乘2和除2并向下取整的操作,使数组内的每个元素都相同。


题目思路:

     对于一个元素,肯定是要先除后乘的才可以转化为目标元素,于是我们只需考虑除2就可以了。由于存在不是整除的情况,除2再乘2导致值

发生改变。用个数组b存可以通过除2到达这个值的元素个数,用数组c记录到达这个值每个元素的操作次数之和,于是当b[i]==n时是可以完成的,

ans=min(ans,c[i]),还有乘2我们没有考虑呢,于是当i%2==0&&b[i/2]==n时,也可以完成目标,此时减少了c[i/2]-b[i]次操作,增加了n-b[i]次操作。


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=100000+1000;
int a[maxn];
int b[maxn];
int c[maxn];
int main()
{
    int maxc,n;
    scanf("%d",&n);
    maxc=0;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        if(a[i]>maxc)
        maxc=a[i];
        int cur=0;
        b[a[i]]++;
        while(a[i]>=1)
        {
            cur++;
            a[i]=a[i]/2;
            b[a[i]]++;
            c[a[i]]+=cur;
        }
    }
    int ans=c[1];
    for(int i=2;i<=maxc;i++)
    {
        if(b[i]==n)
        {
            ans=min(ans,c[i]);
        }
        else if(i%2==0&&b[i/2]==n)
        {
            c[i]=c[i/2]-b[i]+n-b[i];
            b[i]=n;
            ans=min(ans,c[i]);
        }
    }
    printf("%d\n",ans);
    return 0;
}


你可能感兴趣的:(Algorithm,编程,算法,ACM,codeforces)