题目链接:http://codeforces.com/problemset/problem/558/C
题意:
给出n个数,可以乘2,也可以除2,用最少的操作使得最终n个数相等
解题思路:
将每个数 x 乘2,除2,全部都遍历一遍
其中出现奇数时,要再次乘2,直到大于100000
比如:x=3
乘2:6,12,24,……
除2:1
由于1是奇数,又可以由1得到:2,4,8,……
用数组c[i]来记录i出现的次数
用数组step[i]来记录变成i的操作次数
输出c[i] = n时,最小的step[i]
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
#define inf 100005
int a[inf];
int c[inf],step[3*inf];
void up(int x,int s)
{
while(x<=inf)
{
c[x]++;
step[x]+=s;
x<<=1;
s++;
}
}
void go(int x)
{
up(x,0);
int s=0;
while(x)
{
s++;
if(x%2!=0 && x>1)
{
x>>=1;
up(x,s);
}
else
{
x>>=1;
c[x]++;
step[x]+=s;
}
}
}
int main()
{
int n;
scanf("%d",&n);
memset(c,0,sizeof(c));
memset(step,0,sizeof(step));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
go(a[i]);
}
int ans=0x3f3f3f3f;
for(int i=1;i<inf;i++)
{
if(c[i]==n)
{
ans = min(ans,step[i]);
}
}
printf("%d\n",ans);
return 0;
}