codeforce 补题#701
这道题其实不难的,但是我不知道怎么去递归,怎么去循环。后面看了别人的代码后,感觉其实挺容易的,这里总结一下。
法一:递归写法:
要么一直做a/b运算
要么先做b+1运算再做a/b运算
每次na除到0时,记录下ans的最小值
代码1:
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fst first
#define snd second
using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
template<class T>inline void checkmin(T &a,const T &b){if(b<a)a=b;}
template<class T>inline void checkmax(T &a,const T &b){if(b>a)a=b;}
int T;
ll a,b;
int ans=0;
void dfs(ll na,ll nb,int step){
if(na==0){
ans=min(ans,step);
return;
}
if(step==ans)return;
dfs(na/nb,nb,step+1);
dfs(na,nb+1,step+1);
}
void solve(){
ans=0;
cin>>a>>b;
int t=0;
if(b==1)ans++,b++,t++;
ll nowa=a;
while(nowa)nowa/=b,ans++;
dfs(a,b,t);
cout<<ans<<endl;
}
int main(){
cin>>T;
while(T--){
solve();
}
return 0;
}
方法二:
循环求解,思路非常简单
代码如下:
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define forn(i,a,n) for (int i=a; i<n; i++)
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int t;
cin>>t;
while (t--){
int a,b,res=1e18;
cin>>a>>b;
forn(i,0,1e4){
if (b==1 && i==0) continue;//b等于1肯定要继续
int cnt=i;
int c=a,d=b+i;
while (c){
cnt++;
c/=d;
}
res=min(res,cnt);
}
cout<<res<<endl;
}
return 0;
}