CS4335 Assignment 3 Solution Question 1 (a) December 10, 2015

advertisement
CS4335 Assignment 3 Solution
December 10, 2015
Question 1 (a)
Loop from left to right. If the current number is larger than the previous one,
extend the current sub-sequence by 1. Otherwise, reset the current sub-sequence
to contain only the current number. Record and return the maximum one. Total
time complexity is O(n).
Code(without backtracking):
# L is a list of n numbers
def sol1(L):
n = len(L)
if n == 0:
return 0
ans = cur = 1
for i in range(1, n):
if L[i] > L[i-1]:
cur += 1
ans = max(ans, cur)
else:
cur = 1
# ans is the maximum length of increasing sub-sequence
return ans
Question 1 (b)
Loop from left to right. Add the current number to the current sum. If the
current sum is less than 0, reset it. Record the maximum one while looping.
This is a greedy algorithm and the correctness comes from the fact that any
prefix sum of the final solution cannot be negative. The total time complexity
is O(n).
Code(without backtracking):
# L is a list of numbers
def sol2(L):
# if the length of L is zero or there is no positive numbers,
# just return 0(or an empty list if backtracking)
1
n = len(L)
if n == 0 or max(L) <= 0:
return 0
ans = cur = 0
for i in range(n):
cur += L[i]
if cur < 0:
cur = 0
else:
ans = max(ans, cur)
# ans is the maximium sum of sub-sequence
return ans
Question 2
Assume that the distance between any two stations is equal or less than the
maximum distance(C) the car can go. Let D[i] be the cost so far when stopped
and fulfilled at station i, the dynamic programming formula is:
D[i] =
min
∀j, j<i and xi −xj ≤C
D[j] + (xi − xj )/C · Ci
The time complexity is O(n2 ).
Code:
def sol3(x, c, C):
n = len(x)
# d is initialized as a list of n infinity numbers
d = [float(’inf’)] * n
d[0] = 0
for i in range(1, n):
for j in range(i-1, -1, -1):
if x[i]-x[j] > C:
break
d[i] = min(d[i], d[j] + (x[i]-x[j]) / C * c[i])
return d[n-1]
Again, backtracking is left for you.
Question 3
1-planarity, 3-dimensional matching, Bipartite dimension, Capacitated minimum spanning tree and so on.
Remarks: for backtracking, you need to have an extra array. See LCS problem
for an example.
2
Download