题目
分析
根据两个方案,倒着推导,因为每一步一定是原来的值,再与一个容量为1的操作,所以由a/b可以得到:
- a>b,则上一步为(a-b)/b,即a/b一直减1,可以直接做除法,避免TLE
- a<b,则上一步a/(b-a),即b一直减a,可以类似第一种情况去做
代码
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
ll t,a,b;
ll ans;
void Swap(ll &a,ll &b){
ll t = b; b = a; a = t;
}
ll Gcd(ll a, ll b){
if(!b) return a;
return Gcd(b,a%b);
}
int main()
{
// freopen("capacitor.in","r",stdin);
// freopen("capacitor.out","w",stdout);
std::ios::sync_with_stdio(false);
cin>>t;
while(t--){
ans = 0;
cin>>a>>b;
ll k = Gcd(a,b);
a /= k;
b /= k;
while(1){
if(b == 1){ans += a;break;}
ans += a/b;
a %= b;
if(a == 1){ans += b;break;}
ans += b/a;
b %= a;
}
cout<<ans<<endl;
}
return 0;
}