思路:首先可以求出[A,B]内所有数字之和为S的数的个数cnt,然后观察一下,不难发现,最小的那个数字肯定是在cnt=1的时候对应的区间端点。由于具有严格的单调性,即随着区间长度的延长,满足条件的cnt肯定会越来越多。所以先可以数位dp求出cnt。然后二分区间,若cnt>=1,那么说明[A,B]间肯定不止一个符合条件的数字。注意题目要求最小的数字,所以二分区间右端点即可,不要二分左端。这是主要思路。其实就是个裸的数位dp。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=200;
LL dp[20][maxn],digit[20],l,r,s;
LL dfs(LL pos,LL pre,LL limit)
{
if(pos==-1)return pre==s;
if(!limit&&~dp[pos][pre])return dp[pos][pre];
LL ret=0,e=limit?digit[pos]:9;
for(int i=0;i<=e;i++)
{
LL x=pre+i;
ret+=dfs(pos-1,x,limit&&i==e);
}
if(!limit)return dp[pos][pre]=ret;
return ret;
}
LL process(LL n)
{
LL cnt=0;
while(n)
{
digit[cnt++]=n%10;
n/=10;
}
return dfs(cnt-1,0,1);
}
bool ok(LL L,LL R)
{
return (process(R)-process(L-1))>=1;
}
void solve()
{
LL ans,mid,tmp=l;
while(l<=r)
{
mid=(l+r)>>1;
if(ok(tmp,mid))
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
printf("%lld\n",ans);
}
int main()
{
freopen("in.txt","r",stdin);
while(scanf("%lld%lld%lld",&l,&r,&s)!=EOF)
{
memset(dp,-1,sizeof(dp));
solve();
}
return 0;
}