Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1485 Accepted Submission(s): 435
php
#include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef long long ll; int bit[40]; ll f[40][309]; ll dfs(int pos,int m,bool limit,int b) { if(pos==0) return m==0; if(m<0) return 0; if(!limit&&f[pos][m]!=-1) return f[pos][m]; int max_b=(limit?bit[pos]:b-1); ll ans=0; for(int i=0;i<=max_b;i++){ ans+=dfs(pos-1,m-i,limit&&(i==max_b),b); } if(!limit) f[pos][m]=ans; return ans; } ll solve(ll x,int b,int m) { if(x<0) return 0; int pos=0; while(x){ bit[++pos]=x%b; x/=b; } return dfs(pos,m,1,b); } int main() { int p,b,m,cas=0; ll X,Y,k; while(scanf("%d",&p)==1){ printf("Case %d:\n",++cas); memset(f,-1,sizeof(f)); if(p==1){ scanf("%lld%lld%d%d",&X,&Y,&b,&m); if(X>Y) swap(X,Y); printf("%lld\n",solve(Y,b,m)-solve(X-1,b,m)); }else{ scanf("%lld%lld%d%d%lld",&X,&Y,&b,&m,&k); if(X>Y) swap(X,Y); ll tmp1=solve(Y,b,m),tmp2=solve(X-1,b,m); if(k>tmp1-tmp2) puts("Could not find the Number!"); else{ ll l=X,r=Y,ans; while(l<=r){ ll mid=(l+r)>>1; ll tmp=solve(mid,b,m); if(tmp-tmp2>=k) { ans=mid;r=mid-1; } else l=mid+1; } printf("%lld\n",ans); } } } return 0; }