POJ 1019 数学找规律

来源:互联网 发布:驱动精灵软件最新版 编辑:程序博客网 时间:2024/05/06 00:05

Number Sequence
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 36687 Accepted: 10600

Description

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
Input

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)
Output

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

2
8
3
Sample Output

2
2

题意:
一个数列按
1
12
123
1234
……
的方式排列,问第n个数是几

题解:
首先假设:
a[i] 表示的是123~n的个数。

a[1] = 1 –>1
a[2] = 2 –>12
a[3] = 3 –>123
……
但是a[11]!=11
a[11] = 13 –>1234567891011
于是知道计算a[n]时,对123~n的每一个数i实际上加的是1+log10(i).
这样我们便把每一个增序排列的个数算出来了。
然后我们用s[i]存储a[1]~a[i]的和,也就是前缀序列的位数和。这样,我们就能定位n是在哪一个增序列里。
现在问题变成了
==>在12345678910……这样的序列里如何定位第i个数是几。一样的
我们拿出位数来,也就是a[i]。
比如在1234567891011121314这个序列确定第14个数是多少。
我们用1+log10(i)来确定。初始sum = 0。
1占了1+log10(1) + sum = 1位;
2占了1+log10(2) + sum = 2位;
3占了1+log10(3) + sum = 3位;
……
11占了1+log10(11) + sum = 13位;
12占了1+log10 ( 12) + sum = 15位;
13<14<15,所以可以知道第14位的数应该是对应的12的某一位数(也就是要么是1要么是2)。这时我们知道15和14之间差了一个数,那么也就是要求的应该是12的倒数第二个数,也就是12/10=1,所以第14个数是1.

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <map>#include <cmath>#include <queue>#include <vector>#include <string>#define f(i,a,b) for(i = a;i<=b;i++)#define fi(i,a,b) for(i = a;i>=b;i--)using namespace std;#define SIZE 31368unsigned a[SIZE];unsigned s[SIZE];void init(){    int i;    a[1] = s[1] = 1;    f(i,2,SIZE){        a[i] = a[i-1] + (int)log10((double)i) + 1;        s[i] = s[i-1] + a[i];    }}int solve(long long n){    int i;    f(i,1,SIZE)        if(s[i]>=n)            break;    int tem = n - s[i-1];    int a = 0;    for(i = 1;a<tem;i++)        a += (int)log10((double)i)+1;    return (i-1)/(int)pow(10.0,a-tem)%10;}int main(){    int N;    init();    scanf("%d",&N);    while(N--){        long long n;        scanf("%lld",&n);        printf("%d\n",solve(n));    }    return 0;}
0 0
原创粉丝点击