Little Sub and Mr.Potato's Math Problem (找规律)

Little Sub loves math very much. He enjoys counting numbers.

One day, Mr.Potato gives him an interesting math problem. Please help Little Sub solve this problem.

Let's sort the integers  according to alphabetical order. For example, when 

 the order should be: 1,10,11,2,3,4,5,6,7,8,9  We define Q(N,K) as the position of number K in the sorted N numbers. For example, Q(11,2)=4.

Given K and M, please find the smallest N such that Q(N,K)=M.

Input

There are multiple test cases. The first line of the input contains an integer T (1≤T≤100), indicating the number of test cases. For each test case:

The first and only line contains two integers K and M (1≤K≤108, 1≤M≤108).

Output

For each test case, please output the answer in one line. If there is no such N, please output "0" (without quotes).

Sample Input

2
2 4
10000001 100000000

Sample Output

11
1000000088888880

题目大意:

一个函数Q(N,K)=M。表示N个数,按字典序排序,M再第K个的位置上。现在已知K,M,计算最小的N。

思路:

听说可以数位dp,呃呃,一直在推规律。

首先可以分为计算比K小的数中,按字典序还比K小的数有f(K)个。

当f(k)要小于M-1时,则无解。

然后继续寻找比K大的,按字典序是第M-f(k)-1个数是什么,这个数就是N。

注意特判个位数的情况就行了。

 

f是计算正常比K小,按字典序排序还比K小的数的个数。 ff函数是计算N是多少的,主要是根据按字典序排序,还需要多少比K小的数来计算。

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <cmath>
#include <ctime>
using namespace std;
#define ll long long
const int maxn = 1e5 + 100;
const ll mod = 1e9 + 7;
ll p[18];
void init()
{
	p[0] = 0;
	p[1] = 10;
	for (int i = 2;i <= 17;i++)
	{
		p[i] = p[i - 1] * 10;
	}
}
int go(int x)
{
	int cnt = 0;
	while (x)
	{
		x /= 10;
		cnt++;
	}
	return cnt;
}
ll f(ll x)
{
	int cnt = go(x);
	if (cnt == 1)
	{
		return  x - p[cnt - 1] - 1;
	}
	ll sum_ = x - p[cnt - 1];
	for (int i = 1;i < cnt;i++)
	{
		ll sum = x / p[i];
		if (i == cnt - 1)
		{
			sum_ += sum - p[cnt - i - 1];
		}
		else
		{
			sum_ += sum - p[cnt - i - 1] + 1;
		}
	}
	return sum_;
}

ll ff(ll x, int m)
{
	int cnt = go(x);
	ll sum = x;
	ll sum_ = 0;
	for (int i = cnt;;i++)
	{
		sum = sum * 10;
		sum_ = sum - p[i];
		if (sum_ <= m)
		{
			m -= sum_;
		}
		else
		{
			return p[i] + m - 1;
		}
	}
}
int main()
{
	int T;
	cin >> T;
	init();
	while (T--) {
		ll k, m;
		scanf("%lld%lld", &k, &m);
		m = m - f(k) - 1;
		if (m < 0)
		{
			cout << 0 << endl;
			continue;
		}
		if (m == 0)
		{
			cout << k << endl;
			continue;
		}
		cout << ff(k, m) << endl;

	}
	return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值