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;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/89308944