思路:对于每个数字k,先计算如果n为k时,它排第sum位。如果sum=m,那么n=k,如果sum<m,不可能,n>k,那就去找更长的数字拓展范围,例如53,就去找100-529,然后再1000-5299,直到sum=m。
代码:为了期末考试一个月没写代码了,代码写得丑得不行
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<set>
#include<queue>
using namespace std;
typedef long long ll;
ll t,k,m;
ll judge(ll x)
{
ll a[2]={0},cnt=0,pos1=0;
while(x)
{
ll now=x%10;
if(now==1)
{
pos1=cnt;
a[1]++;
}
else if(now==0)
{
a[0]++;
}
else
return 0;
cnt++;
x/=10;
}
if(a[1]!=1||pos1!=cnt-1)
return 0;
return cnt;
}
ll binpow(ll a,ll b)
{
ll ans=1;
while(b>0)
{
if(b&1)
{
ans=ans*a;
}
a=a*a;
b>>=1;
}
return ans;
}
int main()
{
scanf("%lld",&t);
while(t--)
{
scanf("%lld %lld",&k,&m);
if(judge(k))
{
if(m!=judge(k))
{
cout<<0<<endl;
}
else
{
cout<<k<<endl;
}
continue;
}
ll num=k,sum=0,a[100],b[100],co=1;
while(num)
{
ll now=num%10;
b[co++]=now;
num/=10;
}
co--;
for(ll i=1;i<=co;i++)
{
a[co-i+1]=b[i];
}
ll cnt=0,cnt1=1;
for(ll i=1;i<=co;i++)
{
cnt=cnt*10+a[i];
sum+=(cnt-cnt1+1);
cnt1*=10;
}
if(sum==m)
{
printf("%lld\n",k);
}
else if(sum>m)
{
printf("0\n");
}
else
{
ll flag=1,ans=0;
ll l=binpow(10,co);
ll r=k*10-1;
while(sum<m)
{
ll gap=r-l+1;
if(sum+gap>=m)
{
ll xx=m-sum;
ans=l+xx-1;
flag=0;
break;
}
else
{
sum+=gap;
l*=10;
r=r*10+9;
}
/*for(ll i=l;i<=r;i++)
{
sum++;
if(sum==m)
{
ans=i;
flag=0;
break;
}
}
if(flag==0)
break;
if(flag==1)
{
l*=10;
r=r*10+9;
}*/
}
printf("%lld\n",ans);
}
}
return 0;
}