/* Solution to Topcoder SRM 351, D1, 250-Pointer: CoinsExchange. James S. Plank September, 2020 Please see lecture notes in http://web.eecs.utk.edu/~plank/plank/classes/cs302/Notes/Recursion-Review/index.html for explanation. */ #include "coins_exchange.hpp" #include #include #include #include using namespace std; int CE2(int G, int S, int B) { printf("CE2: G:%d S:%d B:%d\n", G, S, B); printf("#1: Do we need gold? (recurse on yes)\n"); /*----------------------------------------------------------------------- */ /* #1: Do we need gold? Yes = Add to our silver needs and do recursion. No = keep going. */ if (G > 0) return G + CE2(0, S+G*11, B); printf("#2: Do we need bronze? (recurse on yes)\n"); /*----------------------------------------------------------------------- */ /* #2: Do we need bronze? Yes = Add to our silver needs and do recursion. No = keep going. */ if (B > 0) return (B+8)/9 + CE2(G, S+(B+8)/9, 0); printf("#3: Do we have enough silver? (return on yes)\n"); /*----------------------------------------------------------------------- */ /* #3: Do we need silver? No = return 0. Yes = keep going. */ if (S <= 0) return 0; printf("#4: Do we have enough gold for silver (return on yes)?\n"); /*----------------------------------------------------------------------- */ /* #4: Do we have enough gold to get all of our silver? Yes = Satisfy silver from gold and return. No = keep going. */ if (-(G*9) >= S) return (S+8)/9; printf("#5: Do we have any gold for silver (recurse on yes)?\n"); /*----------------------------------------------------------------------- */ /* #5: Do we have any gold? Yes = Use all of our gold for silver, and recurse. No = keep going. */ if (G < 0) return -G + CE2(0, S-(-G*9), B); printf("#6: Do we have enough bronze for silver? (return on yes). \n"); /*----------------------------------------------------------------------- */ /* #6: Do we have enough bronze to meet our silver needs? Yes = Satisfy silver from bronze and return. No = keep going. */ if (-B >= S*11) return S; printf("#7: Failure -- return -100000000\n"); return -1000000000; } int CoinsExchange::countExchanges(int G1, int S1, int B1, int G2, int S2, int B2) { int rv; rv = CE2(G2-G1, S2-S1, B2-B1); return (rv >= 0) ? rv : -1; }