杂题-Number Sequence

总时间限制: 1000ms

内存限制: 65536kB

描述

A single positive integer i is given. Write a program to find the digit located in the position i in the sequence of number groups S1S2...Sk. Each group Sk consists of a sequence of positive integer numbers ranging from 1 to k, written one after another.
For example, the first 80 digits of the sequence are as follows:
11212312341234512345612345671234567812345678912345678910123456789101112345678910

输入

The first line of the input file contains a single integer t (1 ≤ t ≤ 10), the number of test cases, followed by one line for each test case. The line for a test case contains the single integer i (1 ≤ i ≤ 2147483647)

输出

There should be one output line per test case containing the digit located in the position i.

样例输入

2
8
3

样例输出

2
2

 

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

const int N = 53000;
long long S_len[N+10], S_suffix[N+10];

void ini()
{
    S_len[0] = 0;
    S_suffix[0] = 0;
    int plus = 1;
    for (int i = 1; i < N; ++i) {
        if (i == 10) ++plus;
        else if (i == 100) ++plus;
        else if (i == 1000) ++plus;
        else if (i == 10000) ++plus;

        S_len[i] = S_len[i-1] + plus;
        S_suffix[i] = S_suffix[i-1] + S_len[i];
    }
    // cout << S_suffix[N-1] << endl;
}

int find_digit(long long idx)
{
    long long* p = lower_bound(S_suffix, S_suffix+N, idx);
    int k = p - S_suffix;
    idx -= *(p-1);
    // printf("Sk : k = %d, idx = %d\n", k, idx);

    p = lower_bound(S_len, S_len+N, idx);
    k = p - S_len;
    idx -= *(p-1);
    // printf("Ak : k = %d, idx = %d\n", k, idx);

    int d = 0;
    int kk = k;
    while (kk) {
        kk /= 10;
        ++d;
    }
    for (int i = 0; i < d - idx; ++i)
        k /= 10;

    return k % 10;
}

int main()
{
    ini();
    int t;
    cin >> t;
    while (t--) {
        long long idx;
        cin >> idx;
        cout << find_digit(idx) << endl;
    }

    return 0;
}

【思路】

主要采取记录前缀和+二分查找的方法

A$_k$ = string(k);

那么 S$_k$=\sum A$_k$

那么S\_suffix(k)=\sum S$_k$

现在我们只需先对S_suffix数组做二分查找,定位到具体的S[k];

再对S数组进行二分查找,定位到具体的A[k];

找到A[k]就非常好办了,直接暴算即可

【细节】

虽然输入范围在int范围内,但如果采取本方法还是必须用long long

为什么呢?

因为存在某个k

S_suffix(k) < INT_MAX < S_suffix(k+1)

那么如果输入的idx恰好属于区间(S_suffix(k), INT_MAX)

此时的二分查找是无效的,因为紧接着下一项是负数

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页