poj 1019(组外偏移->组内偏移)

本文详细阐述了如何通过编程找到数列特定位置的数字,涉及组合数学原理及算法实现,通过实例演示了解决步骤,适用于算法与数据结构的学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Number Sequence
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 31916 Accepted: 9075

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

Source

Tehran 2002, First Iran Nationwide Internet Programming Contest


简单的组合数学。思路是:先判断num是在第几组(题目中的Sk),再计算出组内偏移(用num减去这个组之前的累计数字个数)。然后计算出 那个组的组内偏移位置数字是多少。
需要细心一些。第一次样例没有过是因为sum[i] - num这个计算出来的实际上是组内的倒着数的偏移量,因此需要用belong[i]减去这个值才能得到正数偏移量。
每时每刻都需要知道每个值是 从0计数还是从1计数。为了安全起见,本程序所有计数都 统一从1开始

提交记录:
1、Accepted!

代码:
/*Source Code

Problem: 1019		User: 775700879
Memory: 1192K		Time: 0MS
Language: G++		Result: Accepted
Source Code*/
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       
#include 
       
       
        
        
#include 
        
        
          #include 
         
           #include 
          
            #include 
           
             #include 
             #define MAX_V 500 #define oo 0x3f3f3f3f #define UPPER 2147483647 using namespace std; long long belong[100000] = {0}; long long sum[100000] = {0}; long long strleng(int i) { long long result = 0; while (i != 0) { result++; i /= 10; } return result; } long long get(long long num, long long position) { int i = 0; while (num != 0) { if (i == position) return num % 10; num /= 10; i++; } } long long cal(long long rank, int group) { long long count = 0; long long i; for (i = 1; i <= group; i++) { count += strleng(i); if (count >= rank) { return get(i, count - rank); } } } int main() { int t; long long num; int i, j, k; sum[1] = belong[1] = 1; for (i = 2; ; i++) { belong[i] = belong[i-1] + strleng(i); sum[i] = sum[i-1] + belong[i]; if (sum[i] > UPPER) break; } cin >> t; while (t--) { cin >> num; for (i = 1; sum[i] < num && i < 100000; i++) { } cout << cal(belong[i] - (sum[i] - num), i) << endl; } return 0; }  
            
           
          
        
       
       
      
      
     
     
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值