Chip Exchange has A, B, cA, cB, fA and asks for the minimum random additional chips guaranteeing the target; the code binary-searches the worst distribution.
Math
Problem and code
Useful links.
Written by benbenyaojifen. Try the problem first, then compare your approach with the code.
1#include <bits/stdc++.h>2usingnamespace std;3#define int long long4using i128 = __int128_t;5voidsolve() {6int a, b, ca, cb, k; cin >> a >> b >> ca >> cb >> k;7auto good = [&] (int x) {8if ((i128) a + ((i128) b + x) / cb * ca < (i128) k) returnfalse;9// how many use of change chip10int begin = b / cb, end = (b + x) / cb;11if (begin < end) {12int last;13if (ca >= cb) last = begin;14else last = end -1;15// how many to give to achieve the worst distribution possible16int worst = last * cb + cb -1- b;17if (worst >=0&& worst <= x) {18if ((i128)a + x - worst + ((i128) b + worst) / cb * ca < (i128) k) returnfalse;19 }20 }21returntrue;22 };23int lo =0, hi =1000000000000000000;24// how much we give to b because minima always occur at give all to be or 1 before the multiple of cb25while (lo < hi) {26int mid = lo + (hi - lo) /2;27if (good(mid)) hi = mid;28else lo = mid +1;29 }30 cout << lo <<'\n';31}32signedmain() {33 ios::sync_with_stdio(0); cin.tie(0);34int t; cin >> t;35while (t--) {36solve();37 }38return0;39}
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.
Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.