QDU BelamiYao的一道简单签到题(思维)

BelamiYao的一道简单签到题

发布时间: 2017年6月11日 17:59   最后更新: 2017年6月15日 13:32   时间限制: 300ms   内存限制: 128M

BelamiYao得到了一个数列,但BelamiYao想把数列中所有的数都变成同一个数,然而BelamiYao只有两种nr4数字膜法,每一秒只能使用一种膜法

1.将一个数乘2.

2.将一个数除2,并向下取整。

BelamiYao想问你最少需要花费多少秒才能将数列中所有的数都变成同一个数。

第一行一个整数n代表数列中数字的个数
接下来n个整数。
保证输入所有数据均小于100000

输出一个整数代表答案

  复制
3
4 8 2
2

思路:这题时间给那么少,真心不敢过于暴力(估计时间少写个0)。只需要存储这组数最大值在除2的过程中的所有

的中间值*2^k然后进行枚举(所有可能能变成的值)即可。还有一个点是怎么判断这组数怎么以最小次数变成这个可

能值,这儿可能会想bfs,但是每次都会对标记数组进行memset,所以复杂度颇高。先进行能不能从a[i]变到当前

可能值得判断,不能直接break,能则只需要进行下面的运算便可求得最小次数,假如x->y,当x>y时,对x/2,当

y>x时,对y/2,直到x=y时的操作数便是所求。


Code:

#include <algorithm>
#include <iostream>
#include <string.h>
#include <cstdio>
#include <set>
using namespace std;
const int maxn = 100005;
const int inf = 0x3f3f3f3f;
int a[maxn], ans, up;
set<int> s;
set<int>::iterator it;
void add()
{
	int k = up;
	while(k > 1)
	{
		if(k/2*2 != k && k/2)
		{
			int kk = k/2*2;
			while(kk <= up)
			{
				s.insert(kk);
				kk <<= 1;
			}
		}
		s.insert(k);
		k >>= 1;
	}
	k = 1;
	while(k <= up)
	{
		s.insert(k);
		k <<= 1;
	}
}
int calc(int x, int y)
{
	int cnt = 0;
	while(x != y)
	{
		if(x > y) x /= 2;
		else y /= 2;
		++cnt;
	}
	return cnt;
}
int main()
{
	int n, k, flag, cnt, ej;
	scanf("%d", &n); up = 0;
	for(int i = 0; i < n; ++i)
	{
		scanf("%d", &a[i]);
		up = max(up, a[i]);
	}
	add(); ans = inf;
	for(it = s.begin(); it != s.end(); ++it)
	{
		ej = *it; cnt = 0; flag = 1;
		while(ej%2 == 0) ej /= 2;
		for(int i = 0; i < n; ++i)
		{
			int x = a[i];
			while(x%ej != 0) x /= 2;
			if(x == 0)
			{
				flag = 0;
				break;
			}
			else cnt += calc(a[i], *it);
		}
		if(flag) ans = min(ans, cnt);
	}
	printf("%d\n", ans);
	return 0;
}


继续加油~

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值