Explanation
Notice that the meta is to process shorter tasks before longer tasks.
For some intuition regarding this, think of two tasks that take and time units to complete. Notice that no matter what the deadlines are, it's always optimal to complete the shorter task first.
To prove this more concretely, let's take tasks, with durations and deadlines . Say we complete them in an order such that is the number of the th task completed, making a permutation of through .
The final reward is then
Rearranging the formula, we can get
Try expanding them to see why these two are equal!
From this, we can see that we must minimize smaller values of , which is then equivalent to processing shorter tasks first.
Implementation
Time complexity:
C++
#include <algorithm>#include <iostream>#include <vector>using std::cout;using std::endl;int main() {int task_num;std::cin >> task_num;
Java
import java.io.*;import java.util.*;public class TasksNDeadlines {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int taskNum = Integer.parseInt(read.readLine());int[][] tasks = new int[taskNum][];for (int t = 0; t < taskNum; t++) {StringTokenizer task = new StringTokenizer(read.readLine());
Python
Warning!
Due to Python's constant factor, the below code may TLE on a couple of test cases.
tasks = []for _ in range(int(input())):duration, deadline = [int(i) for i in input().split()]tasks.append((duration, deadline))tasks.sort()time = 0reward = 0for duration, deadline in tasks:time += durationreward += deadline - timeprint(reward)
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!