Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Efficient Scheduling for Maximum Reward with Time Constraints

Tech May 18 2

Problem Overview

Given T time units and n tasks, each task i has a value a_i and a deadline b_i. In each time unit t, you may select one unselected task i where b_i ≥ t to gain a_i. The goal is to maximize the total reward.

Algorithm Strategy

Sort tasks in descending order of value a_i. Use a set to track available time slots. For each task, assign it to the latest possilbe time slot that does not exceed its deadline.

Complexity Analysis

Time compelxity is O(n log n) due to sorting and set operations.

Code Implementation

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
typedef long long int64;
const int MAX_N = 2000010;

struct Task {
    int value, deadline;
    bool operator<(const Task &other) const {
        return value == other.value ? deadline > other.deadline : value > other.value;
    }
};

Task tasks[MAX_N];
set<int> time_slots;

int main() {
    int T, n;
    cin >> T >> n;
    int valid_count = 0;
    int64 total_reward = 0;
    for (int i = 0; i < n; i++) {
        int d, v;
        cin >> d >> v;
        if (d > n) {
            total_reward += v;
        } else {
            tasks[valid_count++] = {v, d};
        }
    }
    for (int i = 1; i <= n; i++) {
        time_slots.insert(i);
    }
    sort(tasks, tasks + valid_count);
    for (int i = 0; i < valid_count; i++) {
        auto it = time_slots.upper_bound(tasks[i].deadline);
        if (it == time_slots.begin()) continue;
        it--;
        total_reward += tasks[i].value;
        time_slots.erase(it);
    }
    cout << total_reward << endl;
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.