uva 679 Dropping Balls

题目:Dropping Balls


题意:有一颗深度为d的二叉树,i个小球从根节点向下落。每个节点上有一个开关,小球落在该节点上时,若开关为开则向右走;反之向左走。小球每经过一次开关,开关的状态改变一次。求第i个小球最终会落到哪个节点上。


思路:

1、模拟。定义一个数组bool a,用来存储开关情况。小球当前位置为k时,像左走为2*k,像右走为2*k+1。(TLE)

2、因为小球的下落是有规律的,假如第j个小球向左,那么j+1个小球一定会向右走。所以只关心最后一个小球的奇偶性即可。


注意:思路2中,如果忘记删除思路1中的a数组的初始化,会超时。


TLE代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<deque>
using namespace std;

int l,d,s;
bool a[(1<<20)]={0};

int main() {
	
	scanf("%d",&l);
	while(l--){
		memset(a,0,sizeof(a));
		scanf("%d%d",&d,&s);
		int n=(1<<d)-1;
		int where=1;
		for(int i=1;i<=s;i++){
			where=1;
			do{
				if(a[where]==false) where*=2;
				else where=where*2+1;
				a[where/2]^=1;
			}while(where<=n);
		}
		printf("%d\n",where/2);
	}
	
	return 0;
}


AC代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<deque>
using namespace std;

int l,d,s;

int main() {
	scanf("%d",&l);
	while(l--){
		scanf("%d%d",&d,&s);
		int where=1;
		do{
			if(s%2==0){
				where=where*2+1;
				s/=2;
			}else{
				where*=2;
				s=(s+1)/2;
			}
			d--;
		}while(d>=2);
		printf("%d\n",where);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值