题目描述:
题目链接: Codeforces Round #200 div1 A Rational Resistance
题目大意:
你有无穷多个阻值为1Ω的电阻,现通过多次串联、并联的方式,使得总阻值为
a
b
\frac{a}{b}
baΩ。请问最少需要多少个1Ω的电阻?
输入格式:
输入仅一行,为整数a和b(1 ≤ a, b ≤
1
0
18
10^{18}
1018),保证
a
b
\frac{a}{b}
ba是不可再约分的,保证有解。
输入格式:
输出仅一行,即所求答案。
样例输入输出:
input
1 1
output
1
input
3 2
output
3
input
199 200
output
200
Note
样例1中,1个便足够。
样例2中, 两个1Ω先并联,即1//1=
1
2
\frac{1}{2}
21Ω,然后再与1个1Ω串联,即
1
2
\frac{1}{2}
21+1=
3
2
\frac{3}{2}
23Ω。
题目分析:
我们先分别考虑一下串联和并联,假设目前已得到阻值为
c
d
\frac{c}{d}
dcΩ,
1、若再串联一个1Ω电阻,即1+
c
d
\frac{c}{d}
dc=
c
+
d
d
\frac{c+d}{d}
dc+dΩ
2、若再并联一个1Ω电阻,即1//
c
d
\frac{c}{d}
dc=
c
c
+
d
\frac{c}{c+d}
c+dcΩ
观察两个结果,发现很相似,那么我们反推:
现在阻值为
a
b
\frac{a}{b}
ba,若a>b,则
a
b
\frac{a}{b}
ba=1+
a
−
b
b
\frac{a-b}{b}
ba−b(串联),若b>a,则
a
b
\frac{a}{b}
ba=1//
a
b
−
a
\frac{a}{b-a}
b−aa(并联)。重复这个过程,最终会得到
1
1
\frac{1}{1}
11,再进行一次便为0。也就是说反过来,从0开始我们能够串联、并联得到a/b,而所需电阻个数就与减的次数相同。而从
a
b
\frac{a}{b}
ba到0这个过程和辗转相减法过程是一样的,但是用减法会超时(
1
0
18
10^{18}
1018),所以用辗转相除法来计算。
附代码:
#include<iostream>
using namespace std;
long long a,b,t,ans;
int main()
{
scanf("%lld%lld",&a,&b);
while(b!=0)
{
ans+=a/b;
t=a%b;
a=b;
b=t;
}
printf("%lld",ans);
return 0;
}