化学变换

来源:互联网 发布:配电网仿真软件 编辑:程序博客网 时间:2024/04/28 23:33

有n种不同的化学试剂。第i种有ai升。每次实验都要把所有的化学试剂混在一起,但是这些试剂的量一定要相等。所以现在的首要任务是把这些化学试剂的量弄成相等。

有两种操作:

·        把第i种的量翻倍,即第i种的量变成2ai。

·        把第i种的量减半,除的时候向下取整,即把第i种的量变成  ai2  。

现在所有的化学试剂的量已知,问最少要变换多少次,这些化学试剂的量才会相等。

样例解释:把8变成4,把2变成4。这样就需要两次就可以了。


Input
单组测试数据。第一行有一个整数n (1 ≤ n ≤ 10^5),表示化学物品的数量。第二行有n个以空格分开的整数ai (1 ≤ ai ≤ 10^5),表示第i种化学试剂的量。
Output
输出一个数字,表示最少的变化次数。
Input示例
34 8 2
Output示例

2

#include <iostream>#include <cstring>using namespace std;const int size = 1e5 + 5;const int maxValue = 2e5 + 5;int input[size];int cost[maxValue];int visit[maxValue];void fun_help(int a, int prevSteps){    if (a > 0)    {        int step = prevSteps;        for (int i = 2*a; i < maxValue; i *= 2)        {            step++;            cost[i] += step;            visit[i] += 1;        }    }}void fun(int a){    int step = 0;    visit[a] += 1;    for (int i = 2*a; i < maxValue; i *= 2)    {        step++;        cost[i] += step;        visit[i] += 1;    }        bool found = false;    step = 0;    if (a & 1)    {        fun_help(a/2, 1);    }    for (int i = a/2; i > 0; i /= 2)    {        step++;        cost[i] += step;        visit[i] += 1;        if (i & 1)        {            fun_help(i/2, step+1);        }    }}int main(){int n;cin >> n;memset(cost, 0, sizeof(cost));memset(visit, 0, sizeof(visit));for (int i = 0; i < n; i++){    cin >> input[i];}for (int i = 0; i < n; i++){    fun(input[i]);}int result = 1e8;for (int i = 0; i < maxValue; i++){    if (visit[i] == n)    {        if (cost[i] < result)        {            result = cost[i];        }    }}cout << result << endl;return 0;}