首页 > 代码库 > poj 1019 Number Sequence , 二分

poj 1019 Number Sequence , 二分

从下面这一有规律的串中,查找第i(1 ≤ i ≤ 2147483647)个位置的数是什么?

11212312341234512345612345671234567812345678912345678910123456789101112345678910......


二分

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef long long LL;
const int maxn = 31270;
LL len[maxn+100], sum[maxn+100],ss[maxn+100];

void init() {
    sum[0] = ss[0] = 0;
    for(int i=1; i<=maxn; ++i) {
        len[i] = (int)log10(i) + 1;
        sum[i] = sum[i-1] + len[i];
        ss[i] = ss[i-1] + sum[i];
        // for(int j=1; j<=i; ++j)
        //    printf("%d",j);
    }
}

void work(int n) {
    int i = lower_bound(ss, ss+maxn, n) - ss;
    /*
    while(ss[i]<n) {
        i++;
    }
    */

    int m = n - ss[i-1];
    int j = lower_bound(sum, sum+maxn, m) - sum;
    /*
    while(sum[j]<m) {
        j++;
    }
    */

    int p = sum[j] - m;

    int ans = j /(int)pow(10, p) % 10;
    printf("%d\n", ans);
}

int main() {
    int i,t;
    init();
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &i);
        work(i);
    }
    return 0;
}


poj 1019 Number Sequence , 二分