USACO · 1539

Chip Exchange

This C++ solution uses mathematical reasoning for USACO 1539 Chip Exchange. Read the reasoning, inspect the code, or try your own test case below.

1539MathMathematical reasoningC++39 lines
Solution043of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Mathematical reasoning

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.

Open official problem ↗View exact source file ↗
Implementation

Problem_1_Chip_Exchange.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    using i128 = __int128_t;
    void solve() {
        int a, b, ca, cb, k; cin >> a >> b >> ca >> cb >> k;
        auto good = [&] (int x) {
            if ((i128) a + ((i128) b + x) / cb * ca < (i128) k) return false;
            // how many use of change chip
            int begin = b / cb, end = (b + x) / cb;
            if (begin < end) {
                int last;
                if (ca >= cb) last = begin;
                else last = end - 1;
                // how many to give to achieve the worst distribution possible
                int worst = last * cb + cb - 1 - b;
                if (worst >= 0 && worst <= x) {
                    if ((i128)a + x - worst + ((i128) b + worst) / cb * ca < (i128) k) return false;
                }
            }
            return true;
        };
        int lo = 0, hi = 1000000000000000000;
        // how much we give to b because minima always occur at give all to be or 1 before the multiple of cb
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (good(mid)) hi = mid;
            else lo = mid + 1;
        }
        cout << lo << '\n';
    }
    signed main() {
        ios::sync_with_stdio(0); cin.tie(0);
        int t; cin >> t;
        while (t--) {
            solve();
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
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.