HDU-6468 zyb的面试(模拟十叉树+dfs)

Problem 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

   看到字典序查询,似乎第一印象是字典树。而这里正好需要它的改版——0~9字典树(临时起名)。而且不同于普通tire tree(字典树),这个题里只要假设它存在就好了。什么叫假设存在呢?就是我们用最大数值来设定一个边界限制深度搜索。拿样例为例,我们从1开始进位搜索(因为是dfs),搜到11,再搜到21,这个时候大于15,直接退出(return ;),每一次成功的深搜(不退出)都要对步数减一,步数为0的时候就找到了所需的数字。

那么显然地,有这样的思路:

  1. 对已有数据范围内进行模拟十叉树式搜索,每一次成功的搜索都要对步数减一,否则直接退出函数。特别注意一点,就是不要把步数参数放在dfs函数的参数列表里。因为在递归的时候只有深入一层(递归一次)才会对步数进行修改,而这里同样对同层元素(同位数)的搜索有步数修改要求,以上设定不能满足这样的规定。

详见代码:

#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <cmath>
#define DETERMINATION main
#define lldin(a) scanf("%lld",&a)
#define din(a) scanf("%d",&a)
#define printlnlld(a) printf("%lld\n",a)
#define printlnd(a) printf("%d\n",a)
#define printlld(a) printf("%lld",a)
#define printd(a) printf("%d",a)
#define reset(a,b) memset(a,b,sizeof(a))
const int INF=0x3f3f3f3f;
using namespace std;
const double PI=acos(-1);
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int mod=1000000007;
///Schlacht von Stalingrad
/**Although there will be many obstructs ahead,
the desire for victory still fills you with determination..**/
ll n,progress;
ll ans;
void deep_search(ll current)
{
    if(progress==0)
       {
           ans=current;
           return ;
       }
    for(int i=0; i<=9; i++)
    {
        if(current==0&&i==0)
            continue;
        if(current*10+i<=n)
        {
            progress--;
            deep_search(current*10+i);
        }
        else
            return ;
    }
}
int DETERMINATION()
{
   //cin.ios::sync_with_stdio(false);
   ll t;
   cin>>t;
   while(t--)
   {
     ans=0;
     cin>>n>>progress;
     deep_search(0);
     cout<<ans<<endl;
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43874261/article/details/89648189