hdu-6468

题意:有一个序列,是1到n的一种排列,排列的顺序是字典序小的在前,那么第k个数字是什么?
例如n=15,k=7, 排列顺序为1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9;那么第7个数字就是15.
那么,如果你处在zyb的场景下,你能解决这个问题吗?

从别人那里搞来个图

题解:可以将这个数看成是一个十叉数,比如1节点的下面有10-19节点, 10节点的下面有100-109节点。我们就可以从1开始往后遍历,每次遍历先把这个节点的下面所有节点的总和加在一起step和k判断,如果step比k小,则表示k比这个节点大,k减去这整个节点的个数,结果往后加一位。如果比k大,则表示答案在这个节点里面,k--,结果乘以10进入这个节点的下一层。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstring>
#include <math.h>
#include <stdlib.h>
#include <time.h>

#define ll long long

using namespace std;

ll findKthNumber(ll n,ll k){
	ll cur = 1;
	--k;
	while(k>0){
		ll step = 0,first = cur,last = cur+1;
		while(first<=n){
			step += min(n+1,last) - first;
			last *= 10;
			first *= 10;
		}
		if(step <= k){
			cur++;
			k -= step;
		}else{
			cur*=10;
			k--;
		}
	}
	return cur;
}

int main(){
	int T;
	ll n,k;
	cin>>T;
	while(T--){
		cin>>n>>k;
		cout<<findKthNumber(n,k)<<endl;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值