The Problem
问题属于dynamics programming大类。
Given
n
n
n items
{
1
,
2
,
.
.
.
,
n
}
\{1,2,...,n\}
{1,2,...,n}, and each has a given nonnegative weight
w
i
w_i
wi and value
v
i
v_i
vi. We are also given a bound
W
W
W.
Goal: select a subset
S
S
S of items, which maximizes
∑
i
∈
S
v
i
\sum_{i\in S}v_i
∑i∈Svi subject to
∑
i
∈
S
w
i
≤
W
\sum_{i\in S}w_i \leq W
∑i∈Swi≤W.
Designing the Algorithm
对于动态规划问题,一般从最后一种情况入手。
在添加最后一个element的时候,不光需要知道 OPT(n-1),也需要知道
W
−
w
n
W-w_n
W−wn,即添加最后一个element时的bound是多少。
Assume that
W
W
W is an integer, and all requests
i
=
1
,
.
.
.
,
n
i = 1, . . . , n
i=1,...,n have integer weights
w
i
w_i
wi. We will have a subproblem for each$ i=0,1,…,n$ and each integer
0
≤
w
≤
W
0≤w≤W
0≤w≤W. We will use
O
P
T
(
i
,
w
)
OPT(i,w)
OPT(i,w) to denote the value of the optimal solution using a subset of the items
{
1
,
.
.
.
,
i
}
\{1, . . . , i\}
{1,...,i} with maximum allowed weight
w
w
w, that is,
O
P
T
(
i
,
w
)
=
max
S
∑
j
∈
S
v
j
OPT(i,w)=\max_S \sum_{j \in S}v_j
OPT(i,w)=Smaxj∈S∑vj
where
S
⊆
{
1
,
.
.
.
,
i
}
S\subseteq \{1,...,i\}
S⊆{1,...,i}
定理(6.8):if
w
<
w
i
w<w_i
w<wi, then
O
P
T
(
i
,
w
)
=
O
P
T
(
i
−
1
,
w
)
OPT(i,w)=OPT(i-1,w)
OPT(i,w)=OPT(i−1,w). Otherwise
O
P
T
(
i
,
w
)
=
max
(
O
P
T
(
i
−
1
,
w
)
,
v
i
+
O
P
T
(
i
−
1
,
w
−
w
i
)
)
OPT(i,w)=\max (OPT(i-1,w), v_i + OPT(i-1,w-w_i))
OPT(i,w)=max(OPT(i−1,w),vi+OPT(i−1,w−wi))
Analyzing the Algorithm
定理(6.9):The Subset-Sum( n , W n , W n,W) Algorithm correctly computes the optimal value of the problem, and runs in O ( n W ) O(nW) O(nW) time.
定理(6.10): Given a table M M M of the optimal values of the subproblems, the optimal set S S S can be found in O ( n ) O(n) O(n) time.
Reference
Algorithm Design (Jon Kleinberg)