Table of Contents

ExplanationImplementation

Unofficial Analysis

Explanation

Notice that the meta is to process shorter tasks before longer tasks.

For some intuition regarding this, think of two tasks that take 55 and 77 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 nn tasks, with durations t1,t2,,tnt_1, t_2, \cdots, t_n and deadlines d1,d2,,dnd_1, d_2, \cdots, d_n. Say we complete them in an order such that aia_i is the number of the iith task completed, making a1,a2,,ana_1, a_2, \cdots, a_n a permutation of 11 through nn.

The final reward is then

(da1ta1)+(da2(ta1+ta2))++(dani=1ntai)(d_{a_1}-t_{a_1})+(d_{a_2}-(t_{a_1}+t_{a_2}))+\cdots+\left(d_{a_n}-\sum_{i=1}^n t_{a_i}\right)

Rearranging the formula, we can get

i=1ndaii=1ntai(n+1i)\sum_{i=1}^n d_{a_i} - \sum_{i=1}^n t_{a_i}(n+1-i)

Try expanding them to see why these two are equal!

From this, we can see that we must minimize smaller values of ii, which is then equivalent to processing shorter tasks first.

Implementation

Time complexity: O(NlogN)\mathcal{O} (N \log N)

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 = 0
reward = 0
for duration, deadline in tasks:
time += duration
reward += deadline - time
print(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!