Professional Documents
Culture Documents
MIT1 204S10 Lec10
MIT1 204S10 Lec10
204 Lecture 10
Greedy algorithms:
K
Knapsack
k ((capital
it l b
budgeting)
d ti )
Job scheduling
Greedy method
Local imp
provement method
Does not look at problem globally
Takes best immediate step to find a solution
Useful in many cases where
Objectives or constraints are uncertain, or
An approximate answer is all thats required
max
px
0i < n
i i
s.t.
w x
0i < n
i i
0 xi <= 1
pi 0, wi 0, 0 i < n
Let M= 1.
Integer solution is {2, 3}, an unexpected result in some contexts.
Greedy solution is {1, 98% of 2}.
If problem has hard constraints, need integer solution.
If constraints are fuzzy, greedy solution may be better.
Knapsack problems
Truck packing: integer knapsack
Packing problem in 2 and 3 dimensions is extension
Investment program:
Greedy knapsack at high level
Can be integer knapsack at individual transaction level
(Highway investment or telecom capital investment programs
often handled as integer problem, with occasionally hard-to
interpret results)
Used to train telecom execs for spectrum auction
weight = w;
not
double[] x= new double[e.length];
int i;
x[i]= 1.0;
upper -= e[i].weight;
}
if (i < e.length)
// If all items not in knapsack
x[i]= (double) upper/ e[i].weight; // Fractional item
return x;
}
ratio:
ratio:
ratio:
ratio:
2.5
2.0
1.67
1.5
wgt:
wgt:
wgt:
wgt:
2
2
3
4
profit:
profit:
profit:
profit:
5.0
4.0
5.0
6.0
in?
in?
in?
in?
1.0
1.0
1.0
0.0
Profit
100
19
27
25
15
Deadline
2
1
2
1
3
Profit/Time
100
19
27
25
15
C (27)
( )
0
1
Time
A (100)
E (15)
3
D, B infeasible
algorithm
Each set k of slots has a value F(k) for all slots i in set
k
This stores the highest free slot before this time
F(k) is defined only for root nodes in sets
Free
Free
F(j), j is root
x
x= used
j any nod
de
can be root of set
10
Set(b);
int[] f = new int[b];
// Highest free slot, job due at i
f[i] = i;
// Sentinel at jobs[0]
for (int i = 1; i < n; i++) {
// Jobs in profit order
int q = jobSet.collapsingFind(Math.min(n, jobs[i].deadline));
if (f[q] != 0) {
// If free slot exists
j[q]
q = i;
// Add job in that slot
int m = jobSet.collapsingFind(f[q] - 1); // Find earlier slot
jobSet.weightedUnion(m, q); // Unite sets
f[q] = f[m];
// In case q is root, not m
}
return j;
// Jobs in optimal set
}
// More comments in download code
11
maxD++;
System.out.println("Jobs done:");
if (j[i]>0) {
System.out.println(" Job "+ jobs[j[i]].name +
" at time "+ i);
}
// And compute and output total jobs, total profit
1
2
3
done: 3, total profit: 142
12
Summary
This job scheduling special case solvable with greedy
algorithm
We revisit more general version with dynamic programming
13
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.