codeforces 558C Amr and Chemistry(位操作)

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值