A. Rational Resistance
Description
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
- one resistor;
- an element and one resistor plugged in sequence;
- an element and one resistor plugged in parallel.
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals . In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 ≤ a, b ≤ 1018). It is guaranteed that the fraction is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number — the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.
input
1 1
output
1
input
3 2
output
3
input
199 200
output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance . We cannot make this element using two resistors.
解题思路
这个题目还是有点麻烦的,没有想到方法真的不好写。
注意到我们可以将一个电阻为 的电阻分为 a/b 和 两个电阻串联得到,又因为 a/b 为整数,因此串联 a/b 个电阻为1的电阻即可
唯一麻烦的就是 , 不过这里有一个特点,我们记任意两个电阻大小为 x1 , x2 ,大小为 的电阻可以看作大小为1的电阻先进行x1和x2次串联分别得到两个大小为 x1和x2 的电阻,然后将 x1 和 x2 并联得到大小为 的电阻,一共操作 x1 + x2 + 1 次,然后我们考虑大小为 的电阻,这个电阻可以看作是大小为 和 的电阻串联得到,而和 分别由 x2 和 x1 个大小为 1的电阻并联所得,总操作次数也是 x1 + x2 + 1 次
这样一来就说明获得大小为 的电阻和获取大小为 的电阻操作次数一致,那么我们获取 和获取 需要的操作次数一样,这样一来,我们又可以将 的电阻拆分为 b/ (a%b) 和 两个电阻的串联,重复最开始的操作,直到分子部分为1或者0,记此时需要获取的电阻为 ,如果y == 1 ,说明目前获取的是 大小的电阻,这个我们让x个大小为1的电阻并联即可得到,如果 y == 0 ,那么显然,这个电阻是不需要获取的。
代码区
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<string>
#include<cmath>
#include<ctime>
#include<vector>
#define bug cout << "**********" << endl
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int Max = 2e6 + 10;
ll n, m;
int main()
{
while (scanf("%I64d%I64d", &n, &m) != EOF)
{
ll sum = n / m; //串联
n %= m;
while(n != 1 && n != 0) //如果最后余下1,那么就是m个并联;如果余下的是0,那么刚好n/m个串联
{
if (n < m)
swap(n, m);
sum += n / m;
n %= m;
}
if (n == 1)
sum += m;
printf("%I64d\n", sum);
}
return 0;
}