import java.util.*; /** * Use a greedy algorithm and a segment tree. * Process the days in order. On each day we will pay for the smallest * number of flights such that there are enough flights leftover in the * following months that we can meet the minimum number that we need to * pay for. * We do this with a segment tree where each leaf node corresponds to an * interval of m months. We store the value for * excess_flights_left_in_interval. * If we do not choose all flights on some day, then we decrease the excess * in all remaining flights in the interval by the amount of flights that * we chose not to take. * Use lazy propagation in the segment tree to make the range updates O(log n). * Time complexity: O(n log n) * * @author Finn Lidbetter */ public class frequent_flier_finn { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long k = sc.nextInt(); long[] flights = new long[n + 2*(m-1)]; for (int i=0; i 0) { if (smallestExcess > flights[i+m-1]) { smallestExcess = flights[i+m-1]; } paidFor[i] = flights[i+m-1] - smallestExcess; segTree.update(i+1, i+m, - smallestExcess); } else { paidFor[i] = flights[i+m-1]; } } long paidSum = 0; for (int i=0; i= maxPos)) { // Partial overlap if (left != null) { left.update(l, r, change); } if (right != null) { right.update(l, r, change); } min = Math.min( (left == null ? INF : left.min), (right == null ? INF : right.min) ); } } public long min(long l, long r) { // Get min value in interval [l, r) propagate(); // Do lazy updates to children if (l <= minPos && maxPos <= r) { return min; } else if (r <= minPos || l >= maxPos) { return INF; } return Math.min( (left == null ? INF : left.min(l, r)), (right == null ? INF : right.min(l, r)) ); } // Does required updates, then lazily updates its children // NOTE: This method must be called before updating or accessing a node public void propagate() { if (lazy != 0) { min += lazy; if (left != null) { left.lazy += lazy; } if (right != null) { right.lazy += lazy; } lazy = 0; } } }