To solve this problem, we need to split a sequence into k consecutive non-empty parts such that each part contains at least one element from a given set S. The solution involves using dynamic programming to compute the elementary symmetric sum of gaps between positions of elements from S in the sequence.
S. Let this list be P.S (length of P) is less than k, it's impossible to split the sequence into k valid parts, so the answer is 0.P (denoted as G). Each gap G[i] is the number of valid split points between P[i] and P[i+1].k-1 of the gaps list G. This sum gives the number of valid ways to split the sequence into k parts, as it represents the sum of products of k-1 distinct gaps (each product corresponds to a valid combination of split points).MOD = 10**9 + 7
def main():
import sys
input = sys.stdin.read().split()
ptr = 0
n = int(input[ptr])
ptr +=1
k = int(input[ptr])
ptr +=1
s_size = int(input[ptr])
ptr +=1
sequence = input[ptr:ptr+n]
ptr +=n
S = set(input[ptr:ptr+s_size])
ptr +=s_size
# Collect positions (1-based) of elements in S
P = []
for idx in range(n):
if sequence[idx] in S:
P.append(idx+1) # using 1-based index
m = len(P)
if m < k:
print(0)
return
# Compute gaps between consecutive positions in P
G = []
for i in range(m-1):
G.append(P[i+1] - P[i])
# Compute elementary symmetric sum of degree (k-1) of G
t = k-1
dp = [0]*(t+1)
dp[0] =1
for g in G:
# Update dp from t down to 1 to avoid overwriting
for j in range(t,0,-1):
dp[j] = (dp[j] + dp[j-1] * g) % MOD
print(dp[t])
if __name__ == "__main__":
main()
S to form the list P.S than k, output 0 immediately.P are calculated. Each gap G[i] gives the number of valid split points between P[i] and P[i+1].dp is used where dp[j] is the sum of products of j distinct gaps. We update this array in reverse order to avoid overwriting values that are still needed for computation. The final result is dp[k-1], which gives the number of valid ways to split the sequence into k parts.This approach efficiently computes the desired result using dynamic programming, ensuring correctness and optimal performance for typical input sizes. The modulo operation is applied at each step to handle large numbers and prevent overflow.
(免責聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進行轉載發(fā)布,不代表本網(wǎng)站的觀點及立場。本文所涉文、圖、音視頻等資料的一切權利和法律責任歸材料提供方所有和承擔。本網(wǎng)站對此資訊文字、圖片等所有信息的真實性不作任何保證或承諾,亦不構成任何購買、投資等建議,據(jù)此操作者風險自擔。) 本文為轉載內容,授權事宜請聯(lián)系原著作權人,如有侵權,請聯(lián)系本網(wǎng)進行刪除。