• 字典序的第K小数字


    今天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的场景下,你能解决这个问题吗

    题解

    https://blog.csdn.net/FJJ543/article/details/81908992

    #include<bits/stdc++.h>
    using namespace std ;
    #define LL long long
    #define INF 0x3f3f3f3f
    #define mod 1000000007
    int FF(int n , int k)
    {
         int curr = 1;
            k = k - 1;
            while (k > 0) {
                long steps = 0, first = curr, last = curr + 1;
                while (first <= n) {
                    steps += min((long)n + 1, last) - first;
                    first *= 10;
                    last *= 10;
                }
                if (steps <= k) {
                    curr += 1;
                    k -= steps;
                } else {
                    curr *= 10;
                    k -= 1;
                }
            }
            return curr;
    }
    
    int main()
    {
    
        int T;
        scanf("%d",&T);
        while(T--)
        {
            int n,k;
            scanf("%d%d",&n,&k);
            k--;
            int cnt=1;
            while(k)
            {
                int st=0 , head=cnt , tail = cnt+1;
                while(head<=n)
                {
                    st+=min(n+1,tail) - head;
                    head*=10;
                    tail*=10;
                }
                if(st<=k)
                {
                    cnt++;
                    k-=st;
                }
                else
                {
                    cnt*=10;
                    k--;
                }
            }
            printf("%d
    ",cnt);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    [模板] 主席树
    [模板] 替罪羊树
    [模板] Treap
    [LUOGU] P4342 [IOI1998]Polygon
    [JOYOI] 1051 选课
    poj 1845 数论(唯一分解定理+分治法求等比数列前n项的和mod m的值)
    poj 2418 bst统计字符串
    hdu 3791 二叉排序树
    hdu 3999 二叉排序树
    toj 3711 水题
  • 原文地址:https://www.cnblogs.com/shuaihui520/p/10547562.html
Copyright © 2020-2023  润新知