import java.util.*; public class vending_font { public static void main(String[] args) { new vending_font(new Scanner(System.in)); } public vending_font(Scanner in) { int N = in.nextInt(); Snack[] snack = new Snack[N]; for (int i=0; i stk = new ArrayDeque(); for (int i=0; i 0) { Snack bestBuyer = stk.pop().getBestBuyer(); if (bestBuyer != null) res += bestBuyer.profit; } } else if (stk.size() == 1) { // Special case, the vending machine works correctly for this snack. // For this special case of cycle, we can take everything. curSnack = stk.pop(); res += curSnack.profit; } else { // We have a cycle. Find the best decision for resolving // the cycle in the graph. Note, if we can find a second buyer // it is always better than skipping our node. But a second buyer's // existance in the cycle is not always the best option for // resolving the cycle. It may be better to skip a low reward. // // Obtain the maximimum reward if we didn't have to pay our // penalty for taking everything in this cycle. // // Our reward is given by this equation: // reward = maxReward - minPenalty long maxReward = 0; long minPenalty = Long.MAX_VALUE; for (Snack cycleSnack : stk) { maxReward += cycleSnack.profit; int penalty = cycleSnack.getBestBuyer().profit; Snack secondBuyer = cycleSnack.getSecondBestBuyer(); if (secondBuyer != null) penalty -= secondBuyer.profit; minPenalty = Math.min(minPenalty, penalty); } res += maxReward-minPenalty; stk.clear(); } } // Print the optimal answer. System.out.println(res); } class Snack implements Comparable { int next, buyPrice, sellPrice, numSnacks, profit; ArrayList buyers; boolean seen; public Snack(Scanner in) { next = in.nextInt()-1; buyPrice = in.nextInt(); sellPrice = in.nextInt(); numSnacks = in.nextInt(); profit = -1; buyers = new ArrayList(); seen = false; } // Add this buyer to our list of button presses that can // buy this snack. void addBuyer(Snack rhs) { rhs.profit = sellPrice - rhs.buyPrice; // Only add this buyer if they make a profit. if (rhs.profit > 0) buyers.add(rhs); } Snack getBestBuyer() { if (buyers.size() < 1) return null; return buyers.get(0); } Snack getSecondBestBuyer() { if (buyers.size() < 2) return null; return buyers.get(1); } public int compareTo(Snack rhs) { return rhs.profit - profit; } } }