zyb的面试

Description
今天zyb参加一场面试,面试官听说zyb是ACMer之后立马抛出了一道算法题给zyb:
有一个序列,是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的场景下,你能解决这个问题吗?

Input
T组样例(T<=100)
两个整数n和k(1<=n<=1e6,1<=k<=n),n和k代表的含义如上文

Output
输出1-n之中字典序第k小的数字

Sample Input

1
15 7

Sample Output

15

思路:完全十叉树

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstdio>
#define mem(a,b)  memset(a,b,sizeof(a))

using namespace std;
typedef long long ll;
const int MAXn=10005;
//const int  mod=1000000007;
int cal(int n,int k){
    int cur=1;
    k=k-1;
    while(k>0){
        int step=0,first=cur,last=cur+1;
        while(first<=n){
            step+=min(n+1,last)-first;
            first*=10;
            last*=10;
        }
        if(step<=k){
            cur++;
            k-=step;
        }
        else{
            cur*=10;
            k-=1;
        }
    }
    return cur;
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        int n,k;
        cin>>n>>k;
        cout<<cal(n,k)<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值