Problem Author: | Yunis Dwai |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
The objective is to choose a_i \in [l_i, r_i] such that \left(\prod a_i\right) \pmod c is minimized. The key constraint is c \le 20, which is very small. This suggests that for any index , we only care about the possible remainders (\pmod c) that the prefix product can take.
For any range [l_i, r_i], there are only distinct values modulo . Specifically, if the range length r_i - l_i + 1 \ge c, then the range contains at least one multiple of every residue 0, 1, \dots, c-1. If the range is shorter, we only need to check the values v \in [l_i, r_i]. In either case, checking at most values per index is sufficient.We use Dynamic Programming:Let dp[i][rem] be a boolean indicating if it's possible to obtain a prefix product congruent to rem \pmod c using the first elements.
To reconstruct the answer, we can store the value used to reach that state.DP State:dp[i][rem] = v, where is the value chosen for a_i such that \left(\text{prefix\_product}_{i-1} \times v\right) \equiv rem \pmod c.Transition:For each possible remainder from dp[i-1], and for each v \in [l_i, \min(r_i, l_i + c - 1)]:
If dp[i][new\_rem] is not yet reached, set dp[i][new\_rem] = v and store the parent remainder .The time complexity is O(\sum n \cdot c^2)
def solve():
n,c=map(int,input().split())
l=list(map(int,input().split()))
r=list(map(int,input().split()))
dp=[[-1]*c for _ in range(n+1)]
dp[0][1%c]=0
for i in range(n):
lo,hi=l[i],r[i]
hi=min(hi,lo+c-1)
for rem in range(c):
if dp[i][rem]!=-1:
for v in range(lo,hi+1):
x=(rem*v)%c
if dp[i+1][x]==-1:
dp[i+1][x]=v
cur=0
for i in range(c):
if dp[n][i]!=-1:
cur=i
break
ans=[]
for i in range(n,0,-1):
v=dp[i][cur]
ans.append(v)
for p in range(c):
if dp[i-1][p]!=-1 and (p*v)%c==cur:
cur=p
break
print(*ans[::-1])
for _ in range(int(input())):
solve()