CSU 2304 Magic Spell 前缀和+二分

http://acm.csu.edu.cn:20080/csuoj/problemset/problem?pid=2304

Description

Otaku is a brilliant magical girl and she is fond of binary. She has an interesting magic spell which can do anything for her. But powerful magic spell is too long to remember, so she needs your wisdom.

Magic spell consists of 0 and 1, arranged in binary numbers, like s1s2s3..sk. Each group sk consists of a sequence of positive integer binary numbers ranging from 1 to k, written one after another. For example 111011011110111001101110010111011100101110...(s1 = 1, s2 = 110, s3 = 11011...)

A single positive integer i is given. Please help Otaku find the digit located in the position i.

Input

Input begins with a line with one integer n (1 ≤ n ≤ 10) denoting the number of test cases.

Each test case begins with a line with an integer i (1 ≤ i ≤ 17440179596) 。

Output

For each test case, print a single integer。

Sample Input

3
3
12
439891743

Sample Output

1
0
1

Hint

Source

改编自 POJ1019

Author

ddh

题目大意:序列s[1]=1,s[2]=110,……s[i]=s[i-1]+i的二进制表示,序列T=s[1]+s[2]+s[3]+……+s[n],现给出i,求序列T的第i位是0还是1。(从1开始)

思路: 前缀和+二分。不过这题数据很水,不用二分都能过掉。我们用a[i]和pos[i]代表s[i]和T[i]的位数(长度),然后二分削减i即可。

#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
#include<cstring>
#include<queue>
#include<set>
#include<algorithm>
#include<iterator>
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

ll a[100005];
ll pos[100005];

int main()
{
    int len=0;
    for(ll i=1;;i++)
    {
        a[i]=a[i-1]+1+log2(i);
        pos[i]=pos[i-1]+a[i];
        if(pos[i]>17440179596)
        {
            len=i;
            break;
        }
    }
    ll n;
    int t;
    scanf("%d",&t);
    int p;
    int ws;
    while(t--)
    {
        scanf("%lld",&n);
        p=upper_bound(pos+1,pos+1+len,n)-pos-1;
        n-=pos[p];
        if(n==0)
        {
            printf("%d\n",p&1);
            continue;
        }
        p=upper_bound(a+1,a+1+len,n)-a-1;
        n-=a[p];
        if(n==0)
            printf("%d\n",p&1);
        else
        {
            ws=1+log2(p+1);
            if((1<<(ws-n)&(p+1))>=1)
                printf("1\n");
            else
                printf("0\n");
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值