2C Numerical Sequence (hard version)

题目

The only difference between the easy and the hard versions is the maximum value of k.

You are given an infinite sequence of form "112123123412345…" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, …, the i-th block consists of all numbers from 1 to i.

So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.

Your task is to answer q independent queries. In the i-th query you are given one integer (k_i). Calculate the digit at the position (k_i) of the sequence.

Input

The first line of the input contains one integer (q (1≤q≤500)) — the number of queries.

The i-th of the following q lines contains one integer (k_i (1≤k_i≤10^{18})) — the description of the corresponding query.

Output

Print q lines. In the i-th line print one digit (x_i (0≤x_i≤9)) — the answer to the query (i, i.e. x_i) should be equal to the element at the position (k_i) of the sequence.

Examples

Input 1

5
1
3
20
38
56

Output 1

1
2
5
2
0

Input 2

4
2132
506
999999999999999999
1000000000000000000

Output 2

8
2
4
1

Note

Answers on queries from the first example are described in the problem statement.

题解

解题思路

这道题数据很大,1e18,常规做法数组是开不下的
我们就按位数来存

(a_i)表示有i位数的数字的总长度:1-9, 10-99;
(b_i)(a_i)的前缀和:1-9, 1-99;
(c_i)是到了第i个时数列的长度,

(c_1) 1-1 + 1-2 + ... + 1-9;
(c_2) 1-1 + 1-2 + ... + 1-99;

代码

#include <cstdio>
#include <algorithm>
#define int long long
using namespace std;
int t, k, a[20], b[20], c[20];
signed main() {
    for(int i = 1; i <= 10; i++) {
        int x = i, l = 1, r = 9;
        while (--x) l *= 10, r = r * 10 + 9;
        a[i] = (r - l + 1) * i;
        b[i] = b[i-1] + a[i];
        c[i] = c[i-1] + (b[i-1] + i + b[i]) * (r - l + 1) / 2;
    }//预处理
    scanf("%lld", &t);
    while (t--) {
        scanf("%lld", &k);
        int d = lower_bound(c+1, c+11, k) - c;
        k -= c[d-1];
        int l = 1, r = 9, x = d;
        while (--x) l *= 10, r = r * 10 + 9;
        int L = l;
        while (l <= r) {
            int mid = (l + r) >> 1;
            if ((2 * b[d-1] +d + (mid - L + 1) * d) * (mid - L + 1) / 2 >= k) r = mid - 1;
            else l = mid + 1;
        }
        k -= (2 * b[d-1] + d + (l - L) * d) * (l - L) / 2;
        d = lower_bound(b+1, b+11, k) - b;
        k -= b[d-1];
        int ans = 1, num;
        for(int i = 1; i < d; i++) ans *= 10;
        num = (k - 1) / d;
        k -= num * d;
        ans += num;
        k = d - k;
        while (k--) ans /= 10;
        printf("%lld
", ans % 10);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shawk/p/12792925.html