Skip to content

Commit c51e988

Browse files
authored
Create day003sol02.cpp
1 parent 96346b5 commit c51e988

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Submission Link: https://codeforces.com/contest/343/submission/355828800
2+
3+
/*
4+
Problem: Find the mininmum number of 1 ohm resistance needed to make equivalent resistance a/b
5+
6+
The Calkin-Wilf Tree
7+
This problem can be modeled using the Calkin-Wilf Tree, a binary tree that generates every positive rational number exactly once.
8+
Starting from 1/1, the two possible operations are:
9+
1. Series: a/b -> (a+b)/b (Moves to the Right Child)
10+
2. Parallel: a/b -> a/(a+b) (Moves to the Left Child)
11+
12+
Approach: If a resistance a/b can be obained with k resistors then it is clear that we can get resistance (a+b)/b(if 1 ohm in series) or
13+
a/(a+b)(if 1 ohm in parellel) with k+1 resistance. So we just go in reverse direction if a is greater than b then the last step must have been adding resistors
14+
in series so we add a/b to our answer and make a equal to a%b.. similarly if b is greater than a then The last step must have been adding resistors in parallel so
15+
we add b/a in answer and make b=b%a. This process continues untile either a or b becomes zero as either of a and b can become zero only when one is
16+
completely divisible by other and in this case we will get minimum number of resistor as the quotient.
17+
18+
Time Complexity: O(log(min(a, b))) as it is equivalent to the Euclidean GCD algorithm
19+
*/
20+
21+
#include <bits/stdc++.h>
22+
using namespace std;
23+
24+
int main() {
25+
long long a,b;
26+
cin>>a>>b;
27+
long long ans=0;
28+
while(a>0 && b>0) {
29+
if(a>b) {
30+
ans+=a/b;
31+
a=a%b;
32+
}
33+
else {
34+
ans+=b/a;
35+
b=b%a;
36+
}
37+
}
38+
cout<<ans<<endl;
39+
}

0 commit comments

Comments
 (0)