1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ /*
5+ We want minimum number of 1-ohm resistors needed
6+ to build resistance = a / b
7+
8+ Allowed operations (each consumes exactly 1 resistor):
9+
10+ 1. Series:
11+ R = Re + 1
12+ (fraction increases, used when R > 1)
13+
14+ 2.Parallel:
15+ R = Re / (Re + 1)
16+ (fraction becomes smaller, used when R < 1)
17+
18+ -----------------------------------------------
19+ KEY OBSERVATION
20+
21+ Reverse-thinking makes problem easy:
22+
23+ Instead of building a/b from 1,
24+ go BACKWARDS from a/b to 1/1.
25+
26+ When:
27+ a >= b → fraction > 1
28+ means fraction was formed by SERIES operations
29+ so we repeatedly do:
30+ a = a - b
31+ Each subtraction corresponds to ONE resistor
32+
33+ Number of such subtractions = a / b
34+ (integer division)
35+
36+ Then we reduce:
37+ a %= b
38+
39+ -----------------------------------------------
40+
41+ When:
42+ b > a → fraction < 1
43+ means fraction was formed by PARALLEL operations
44+ so we repeatedly do:
45+ b = b - a
46+
47+ Number of such subtractions = b / a
48+
49+ Then we reduce:
50+ b %= a
51+
52+ -----------------------------------------------
53+
54+ This is EXACTLY what Euclidean Algorithm does.
55+ But instead of counting steps,
56+ we SUM UP all quotients.
57+
58+ The sum = minimum number of resistors.
59+
60+ And problem guarantees there is always a solution,
61+ so it always eventually reaches (1,1).
62+ */
63+
64+ long long minResistors (long long a, long long b) {
65+
66+ long long ans = 0 ;
67+
68+ while (a && b) {
69+
70+ // If numerator >= denominator
71+ if (a >= b) {
72+ ans += a / b; // number of series operations needed
73+ a %= b; // continue reducing
74+ }
75+ else {
76+ ans += b / a; // number of parallel operations needed
77+ b %= a; // continue reducing
78+ }
79+ }
80+
81+ return ans;
82+ }
83+
84+ int main () {
85+ long long a, b;
86+ cin >> a >> b;
87+
88+ cout << minResistors (a, b);
89+ }
90+
91+
92+ // Submission Link:- (https://codeforces.com/contest/343/my)
0 commit comments