Task Scheduling
Problem Statement :
You have a long list of tasks that you need to do today. To accomplish task you need minutes, and the deadline for this task is . You need not complete a task at a stretch. You can complete a part of it, switch to another task, and then switch back. You've realized that it might not be possible to complete all the tasks by their deadline. So you decide to do them in such a manner that the maximum amount by which a task's completion time overshoots its deadline is minimized. Input Format The first line contains the number of tasks, . Each of the next lines contains two integers, and . Output Format Output lines. The line contains the value of the maximum amount by which a task's completion time overshoots its deadline, when the first tasks on your list are scheduled optimally. See the sample input for clarification.
Solution :
Solution in C :
In C :
#include <stdio.h>
#include <stdlib.h>
struct task {
int l_cost, cost, r_cost, total_cost;
int time, max_over;
struct task *l, *r;
};
void update_task(struct task *t) {
int cur_over, max_over;
max_over = t->cost - t->time;
if (t->l) {
t->l_cost = t->l->total_cost;
max_over += t->l_cost;
cur_over = t->l->max_over;
if (cur_over > max_over) max_over = cur_over;
} else {
t->l_cost = 0;
}
if (t->r) {
t->r_cost = t->r->total_cost;
cur_over = t->r->max_over + t->l_cost + t->cost;
if (cur_over > max_over) max_over = cur_over;
} else {
t->r_cost = 0;
}
t->total_cost = t->l_cost + t->cost + t->r_cost;
t->max_over = max_over;
}
struct task *new_task(int time, int cost) {
struct task *t;
t = malloc(sizeof(struct task));
t->l = t->r = 0;
t->time = time;
t->cost = cost;
update_task(t);
return t;
}
void free_task(struct task *t, int recur) {
if (t) {
if (recur) {
free_task(t->l, recur);
free_task(t->r, recur);
}
free(t);
}
}
void insert_task(struct task **tree, struct task *t) {
struct task *cur_task, **next_tree;
if (cur_task = *tree) {
next_tree = (t->time < cur_task->time) ? &(cur_task->l) : &(cur_task->r);
insert_task(next_tree, t);
update_task(cur_task);
} else {
*tree = t;
}
}
int main(void) {
int i, num_tasks, task_due, task_minutes;
struct task *tree = 0;
scanf("%d", &num_tasks);
for (i = 0; i < num_tasks; ++i) {
scanf("%d %d", &task_due, &task_minutes);
insert_task(&tree, new_task(task_due, task_minutes));
printf("%d\n", tree->max_over >= 0 ? tree->max_over : 0);
}
free_task(tree, 1);
return 0;
}
Solution in C++ :
In C++ :
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cctype>
#include <numeric>
#include <queue>
#include <iostream>
#include <iomanip>
#include <sstream>
#define FOR(i,s,e) for(int i=(s);i<(int)(e);i++)
#define FOE(i,s,e) for(int i=(s);i<=(int)(e);i++)
#define ALL(x) (x).begin(), (x).end()
#define CLR(s) memset(s,0,sizeof(s))
#define PB push_back
#define EARLY if(found)return;
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef map<int,int> mii;
typedef vector<int> vi;
#define x first
#define y second
#define L(p) ((p)*2+1)
#define R(p) ((p)*2+2)
const int N = 203600*4;
const int INF = 2036000;
int mx = 0;
int node[N]; // store minimum
bool up[N]; // updated, not yet spread
int ex[N]; // extra to add
void Init() {
CLR(node);
CLR(ex);
CLR(up);
}
void Upd(int p, int a) {
up[p] = 1;
ex[p] += a;
node[p] += a;
}
void Push(int p) {
// if (up[p]) {
// Propagate the flipping effects to children...
// printf("Push %d to child...\n", ex[p], p);
Upd(L(p), ex[p]);
Upd(R(p), ex[p]);
up[p] = ex[p] = 0; // reset. . .
// }
return;
}
// range add
void Upd(int p, int s, int e, int u, int v, int a) { // [s, e)
mx = max(mx, p);
u = max(u, s);
v = min(v, e);
if (u >= v) return;
if (u == s && v == e) {
node[p] += a;
ex[p] += a;
up[p] = 1;
} else {
Push(p);
int md = s+e>>1;
Upd(L(p), s, md, u, v, a);
Upd(R(p), md, e, u, v, a);
node[p] = max(node[L(p)], node[R(p)]);
}
// printf("On Upd [%d %d) + %d: [%d %d) = %d\n", u, v, a, s, e, node[p]);
}
// range max
int Que(int p, int s, int e, int u, int v) {
// printf("At [%d, %d): ", s, e);
Push(p);
// if (u>=e || v<=s) return INF;
u = max(u, s);
v = min(v, e);
if (u >= v) return -INF;
int ret;
if (u==s && v==e) {
ret = node[p];
} else {
int md = s+e>>1;
int t1 = Que(L(p), s, md, u, v);
int t2 = Que(R(p), md, e, u, v);
ret = max(t1, t2);
}
// printf("Ret[%d, %d) = %d\n", s, e, ret);
return ret;
}
int u;
void Trace() {
FOR(i,0,u) {
printf("[%d] = %d\n", i, Que(0, 0, u, i, u));
}
}
int main() {
int n = 103600;
//n = 16;
u = 1;
while (u<n) u<<=1;
Init();
FOR(i,0,u) {
// printf("[%d %d)\n", i, u);
Upd(0, 0, u, i, u, -1);
}
//Trace();
int mx = 0;
int T; scanf("%d", &T);
while (T--) {
int d, m;
scanf("%d%d", &d, &m);
mx = max(mx, d);
Upd(0, 0, u, d-1, u, m);
int ans = Que(0, 0, u, 0, mx);
if (ans < 0) ans = 0;
printf("%d\n", ans);
}
return 0;
}
Solution in Java :
In Java :
import java.util.*;
import java.io.*;
class Solution
{
BufferedReader input;
BufferedWriter out;
StringTokenizer token;
int[] ST;
int[] add;
void update(int s,int e,int x,int a,int b,int v)
{
if(s > b || e < a)return;
if(s >= a && e <= b)
{
add[x] += v;
return;
}
add[2*x+1] += add[x];
add[2*x+2] += add[x];
add[x] = 0;
update(s,(s+e)/2,2*x+1,a,b,v);
update((s+e)/2+1,e,2*x+2,a,b,v);
ST[x] = Math.max(ST[2*x+1]+add[2*x+1],ST[2*x+2]+add[2*x+2]);
}
void build(int s,int e,int x)
{
if(s==e)
{
ST[x] = -s;
return;
}
build(s,(s+e)/2,2*x+1);
build((s+e)/2+1,e,2*x+2);
ST[x] = Math.max(ST[2*x+1],ST[2*x+2]);
}
int query(int s,int e,int x,int a,int b)
{
if(s > b || e < a)return 0;
if(s >= a && e <= b)
{
return ST[x]+add[x];
}
add[2*x+1] += add[x];
add[2*x+2] += add[x];
add[x] = 0;
ST[x] = Math.max(ST[2*x+1]+add[2*x+1],ST[2*x+2]+add[2*x+2]);
int first = query(s,(s+e)/2,2*x+1,a,b);
int second = query((s+e)/2+1,e,2*x+2,a,b);
return Math.max(first,second);
}
void solve() throws IOException
{
input = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
int T = nextInt();
int maxD = 4*(100000+3);
ST = new int[maxD];
add = new int[maxD];
build(0,100000,0);
for(int t = 0; t < T; t++)
{
int D = nextInt();
int M = nextInt();
update(0,100000,0,D,100000,M);
out.write(""+query(0,100000,0,0,100000));
out.newLine();
}
out.flush();
}
int nextInt() throws IOException
{
if(token == null || !token.hasMoreTokens())
token = new StringTokenizer(input.readLine());
return Integer.parseInt(token.nextToken());
}
Long nextLong() throws IOException
{
if(token == null || !token.hasMoreTokens())
token = new StringTokenizer(input.readLine());
return Long.parseLong(token.nextToken());
}
String next() throws IOException
{
if(token == null || !token.hasMoreTokens())
token = new StringTokenizer(input.readLine());
return token.nextToken();
}
public static void main(String[] args) throws Exception
{
new Solution().solve();
}
}
Solution in Python :
In Python3 :
def returnIndex(array,number):
if not array:
return None
if len(array) == 1:
if number > array[0]:
return 0
else:
return None
si = 0
ei = len(array)-1
return binarySearch(array,number,si,ei)
def binarySearch(array,number,si,ei):
if si==ei:
if number >= array[si]:
return si
else:
return si-1
else:
middle = (ei-si)//2 +si
if number > array[middle]:
return binarySearch(array,number,middle+1,ei)
elif number < array[middle]:
return binarySearch(array,number,si,middle)
else:
return middle
def addJob(length, array, deadline,minutes,late):
if length < deadline:
for i in range(deadline-length):
array.append(i+length)
length = deadline
minLeft = minutes
index = returnIndex(array,deadline-1)
if index != None:
while index >=0 and minLeft >0:
array.pop(index)
index -= 1
minLeft -=1
while minLeft >0 and array and array[0] < deadline:
array.pop(0)
minLeft -=1
late += minLeft
return late,length
if __name__ == '__main__':
n = int(input().strip())
time = 0
length = 0
nl = []
late = 0
for op in range(n):
job = input().split(' ')
late,length = addJob(length,nl,int(job[0]),int(job[1]),late)
print(late)
View More Similar Problems
Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →Maximum Element
You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each
View Solution →Balanced Brackets
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra
View Solution →Equal Stacks
ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of
View Solution →