京都大学 情報学研究科 知能情報学専攻 2019年2月実施 基礎科目 F1-1
Author
祭音Myyura (co-authored with GPT 5.6 SOL)
Description
Q.1.1
Given two sequences of length , write pseudocode of an -time algorithm to find a longest common subsequence. Note that a subsequence does not necessarily have to be contiguous. For example, if and , the sequence is a common (but not longest) subsequence of and .
Q.1.2
Given a sequence of permuted integers from 1 to , write pseudocode of an -time algorithm to find the length of the longest monotonically increasing subsequence.
题目描述
- 给定两个长度均为 的序列,写出一个 时间算法的伪代码,求一个最长公共子序列。子序列不要求连续;例如 、 时, 是公共子序列,但不是最长者。
- 给定由整数 的一个排列构成的序列,写出一个 时间算法的伪代码,求最长严格单调递增子序列的长度。
Kai
Q.1.1
Let be the length of a longest common subsequence of prefixes and . Store one predecessor direction for reconstruction.
LCS(X[1..n], Y[1..n])
for i = 0 to n
L[i, 0] = 0
for j = 0 to n
L[0, j] = 0
for i = 1 to n
for j = 1 to n
if X[i] = Y[j]
L[i, j] = L[i-1, j-1] + 1
P[i, j] = DIAGONAL
else if L[i-1, j] >= L[i, j-1]
L[i, j] = L[i-1, j]
P[i, j] = UP
else
L[i, j] = L[i, j-1]
P[i, j] = LEFT
i = n; j = n; S = empty list
while i > 0 and j > 0
if P[i, j] = DIAGONAL
prepend X[i] to S
i = i - 1; j = j - 1
else if P[i, j] = UP
i = i - 1
else
j = j - 1
return S
The recurrence is
There are table entries, each computed in constant time; reconstruction takes . Thus the running time is and the space usage is .
Q.1.2
Maintain tail[l], the smallest possible final value of an increasing subsequence of length found so far.
LIS-LENGTH(A[1..n])
length = 0
for i = 1 to n
l = LOWER-BOUND(tail[1..length], A[i])
// first index l with tail[l] >= A[i]
if no such index exists
length = length + 1
tail[length] = A[i]
else
tail[l] = A[i]
return length
Replacing tail[l] by a smaller value preserves an extendable subsequence of length ; appending beyond the current last tail increases the optimum length by one. Therefore, after every iteration, length equals the longest increasing-subsequence length of the processed prefix. Each lower-bound search costs , so the total time is
with space.