码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1781 In Danger Joseph环 位运算解法

时间:2014-06-14 00:28:32      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   http   tar   ext   

Joseph环,这次模固定是2.如果不是固定模2,那么一般时间效率是O(n),但是这次因为固定模2,那么可以利用2的特殊性,把时间效率提高到O(1)。

规律可以看下图:

bubuko.com,布布扣

具体详细解析请看大师Knuth的Concrete mathematics。


补上纯粹利用位运算写的程序:

作者:靖心 http://blog.csdn.net/kenden23/article/details/30232645

int substraHighBit(int y)
{
	int x = y;
	x = x | (x>>1);
	x = x | (x>>2);
	x = x | (x>>4);
	x = x | (x>>8);
	x = x | (x>>16);
	return y & (x >> 1);
}

#include <cstdio>
int main()
{
	int xy, z;
	char e;
	while (scanf("%d %c %d", &xy, &e, &z) && xy)
	{
		while (z--) xy = (xy << 3) + (xy << 1);
		printf("%d\n", substraHighBit(xy) << 1 | 1);
	}
	return 0;
}


POJ 1781 In Danger Joseph环 位运算解法,布布扣,bubuko.com

POJ 1781 In Danger Joseph环 位运算解法

标签:class   blog   code   http   tar   ext   

原文地址:http://blog.csdn.net/kenden23/article/details/30232645

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!