We need to solve a DP problem: given a sequence x[1..N] (0..255), initial y0 = 128, then for each step n from 1..N, we choose a codebook index kn (value C[kn]) and compute y_n = clamp(y_{n-1} + C[kn], 0, 255). Goal: minimize sum_{n=1}^N (x_n - y_n)^2.
Constraints: N up to 20000, M up to 16. So we need efficient DP, perhaps O(N * S) where S is number of possible y states (256). Since y is clamped to [0,255], it's an integer 0..255. The DP state: dp[n][y] = minimal sum of squares up to step n with y_n = y. Then transition: dp[n][y] = min over c in C such that clamp(prev + c) = y of dp[n-1][prev] + (x_n - y)^2. This is typical DP with 256 states per step, and transitions from each prev to y via c. Since M is <=16, each step we can update dp[n][y] from dp[n-1][prev] for each c and prev that maps to y. But naive: for each y, iterate over possible (prev, c) that produce y. Or iterate over prev and c to update next state. Complexity O(N * 256 * M) = N * 256 * 16 ≈ N * 4096 = 20000 * 4096 = 81.92 million. That's borderline but maybe okay in C++ but Python? 81M operations maybe heavy but could be optimized. Since N up to 20000, 256*M = 4096, total ~82M. In Python, 82M loops might be too slow. But we can optimize: use list of length 256, and for each step, compute new array newdp = [inf]*256. Then for each prev in 0..255, for each c in C: y = clamp(prev + c, 0, 255); candidate = dp[prev] + (x_n - y)^2; if candidate < newdp[y], update. That's 256 * M = up to 4096 operations per step, total ~82M. In Python, 82M simple integer operations may be okay if we use efficient loops? Possibly using for loops with Python's overhead may be borderline (e.g., 0.1 microsecond per operation? Actually Python ~50-100 ns for very simple arithmetic? No, Python overhead is high: a simple loop with 1e7 iterations takes about 0.5 seconds? Let's approximate: 10^7 simple operations ~0.2-0.3 sec? Actually typical Python can do about 50 million simple integer ops per second? But loops with conditionals may be slower. 82M might take 2-4 seconds, maybe okay if well-coded and using PyPy. But the problem might be from an old contest expecting C/C++ solution. However we can perhaps do better using something like BFS? But 82M is fine.
But note: we also have to handle up to multiple datasets. The total N across datasets could be large. But we can just process each dataset with O(N * 256 * M). Since M <= 16, it's okay.
One nuance: The codebook values can be negative and positive, so transitions from prev to y. However we must consider that clamp may affect the actual delta applied. For DP, we can compute y = min(max(prev + c, 0), 255). So the transition is deterministic.
Initialize: dp0[y] = INF except dp0[128] = 0. Actually before any input, we have y0 = 128. But we consider step 1: we choose c1 leading to y1. So dp[1][y] = (x1 - y)^2 for y reachable from y0=128 via one step. So we can initialize dp as dp[128] = 0 for step 0. Then iterate n from 1 to N: compute newdp.
Edge case: Codebook could have duplicate values? Possibly but M up to 16; duplicates maybe possible but not harmful.
Let's test on sample.
We'll implement clamp function: def clamp(v): return 0 if v<0 else 255 if v>255 else v.
Now DP: For each step, for prev in 0..255: if dp[prev] is not INF: for c in C: y = clamp(prev + c); new = dp[prev] + (x_n - y)^2; if new < newdp[y]: newdp[y] = new.
But we can reduce loops: Since dp[prev] may be INF for many states initially? Initially only 128 is non-INF. Over steps, states may spread, but after few steps, many states become reachable? Since codebook may allow any movement? Possibly all 256 states reachable eventually. But anyway we still iterate over all prev states. That's okay.
Potential optimization: Precompute for each prev, the list of (y, cost_add) maybe? But cost_add depends on x_n, so cannot precompute (x_n - y)^2 changes each step. However we can compute per step: for each prev, for each c, compute y, then compute square error. That's fine.
Alternative approach: Since M is small, we could use DP with state as previous y, but that's what we are doing.
Memory: dp array of size 256 (int). Use two arrays.
Implementation details:
- Read input lines. The dataset ends with "0 0".
- For each dataset, read N M.
- Then read M lines of codebook integers.
- Then read N lines of x values.
- Compute answer.
Edge Cases:
- Codebook might contain values that cause no change? e.g., 0.
- Clamping: If prev + c < 0, y=0; if >255, y=255.
- The sum of squares could be large (each term up to 255^2 ≈ 65025, N up to 20000 so total up to ~1.3e9 fits in 32-bit signed? Actually 65025 * 20000 = 1,300,500,000 < 2^31, but with minimization might be less. So 64-bit safe.
Let's implement with Python using list of ints, INF = 10**18.
We need to consider speed: We'll use local variables and perhaps use for loops inside. Also note that reading input: we can use sys.stdin.read() to read all and parse integers for speed.
Implement:
import sys
def solve():
data = list(map(int, sys.stdin.read().split()))
it = iter(data)
out_lines = []
INF = 10**18
while True:
N = next(it); M = next(it)
if N == 0 and M == 0:
break
C = [next(it) for _ in range(M)]
X = [next(it) for _ in range(N)]
# dp array size 256
dp = [INF]256
dp[128] = 0
for x in X:
newdp = [INF]256
# For each prev y where dp[prev] != INF
# Since many might be INF, we can skip, but checking INF each time is cheap. Or we can gather reachable states but not needed.
for prev in range(256):
prev_cost = dp[prev]
if prev_cost == INF:
continue
for c in C:
ny = prev + c
if ny < 0:
ny = 0
elif ny > 255:
ny = 255
# compute cost
# We can compute diff = x - ny, square = diffdiff
cost = prev_cost + (x - ny)(x - ny)
if cost < newdp[ny]:
newdp[ny] = cost
dp = newdp
ans = min(dp) # after N steps, we need minimum over final y
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
Check sample:
Input:
2 7
4 2 1 0 -1 -2 -4 131 137 ... Actually they are given line by line but all ints.
But careful: In sample input, they list each value on separate line, but reading all ints works.
Let's test manually with given sample.
But wait: The codebook values are given as separate lines, but order may be important? They are just set; order doesn't matter.
But there is nuance: In sample input, for 10 7 dataset, codebook is -4, -2, -1, 0, 1, 2, 4 (i.e., sorted descending). That's fine.
For dataset: 5 1, codebook = [255]; then X = [0,0,0,0,0]. Let's simulate: y0=128; step1: only c=255, y1 = clamp(128+255=383 -> 255). error = (0-255)^2=65025. y2: prev=255, +255=510 -> clamp=255, error again 65025, sum=5*65025=325125. Output matches.
Dataset 4 1: codebook = [0]; X = [255,0,255,0]. Starting y0=128; each step c=0, so y remains 128 always. errors: (255-128)^2=16129? Actually 127^2=16129? 255-128=127, square=16129; second: (0-128)^2=16384; third: 16129; fourth:16384; sum=16129+16384+16129+16384=65026? Wait 16129+16384=32513; double =65026. Yes matches sample.
So DP works.
Now complexity: For each x, we loop over 256 prevs and M codes. But we skip INF prevs: At start, only 128; after step 1, at most M distinct y's (maybe fewer due to clamping duplicates). Actually each prev can produce multiple y's, but number of reachable states quickly becomes 256 because codebook may allow covering all. But we still iterate all 256. That's fine.
But maybe we can accelerate by precomputing for each prev the list of possible next y's and the necessary delta? That would be same loop: for each prev, for each c, compute y. That is 256 * M per step. Could we vectorize with numpy? But standard Python solution likely accepted if optimized.
But N=20000, M=16 => 2000025616=81,920,000. In Python, with simple loops, might take ~2-3 seconds. Possibly okay in PyPy. In ICPC, Python may be accepted if optimized.
But we could reduce by noticing that M <= 16, but we can also process as: for each c, for each prev, update newdp[y]. That's same.
We can also attempt to use BFS-like technique: Since dp[prev] might be large, but we still loop.
But there may be an even more efficient solution using shortest path in a graph with layers, but DP with 256 states is standard.
Another perspective: Since y is bounded to 0..255, we can think of DP as a linear DP with small state. That's the intended solution.
Let's check potential improvements: Use array module or list comprehension? Possibly use for c in C: for prev in range(256): etc. This may have better memory locality? But essentially same.
One small optimization: Precompute clamp for each prev and c? Since c is small, we could compute ny = prev + c, then if ny<0: ny=0; elif ny>255: ny=255; else ny. Since Python condition checks are slow, we could precompute for each prev and each c the resulting y. Because codebook fixed, we can precompute a next_state[prev][c] = clamp(prev + c). That would be a 2D list of size 256 x M. Precompute once per dataset. Then inside loop, ny = next_state[prev][c]. This avoids repeated if checks. Might be faster.
Also we can compute square diff: (x - ny) ** 2. Could precompute (x - ny)^2 for all ny? Since x changes each step, we could compute an array sqdiff[ny] = (x - ny)^2 for ny 0..255, precompute once per step. Then inside loop, cost = prev_cost + sqdiff[ny]. That avoids computing square each time.
So per step:
-
Compute sqdiff = [(x - y)**2 for y in range(256)] # list of 256 ints
-
Then for prev in range(256): if dp[prev] != INF: for c in C: ny = nxt[prev][c]; newcost = dp[prev] + sqdiff[ny]; if newcost < newdp[ny]: newdp[ny] = newcost.
Alternatively, we could loop over c outer, then prev, but same.
Precompute nxt: nxt[prev][c_index] = clamp(prev + C[c_index]).
Complexity same but with less computation per inner iteration.
Also we can break early if dp[prev] is INF. But we already check.
Given that M <= 16, and 256*16=4096 per step, with N=20000 => 81.9 million iterations. Each iteration does a few array lookups and integer addition/comparison. That might be okay in PyPy if optimized.
But we should also consider that we have to run for multiple datasets. So total iterations may be larger. But problem statement doesn't give total N across datasets, but sum could be up to maybe 20000 per dataset, with many datasets? Possibly they keep sum moderate.
We can implement this with the precomputed nxt and sqdiff.
Another micro-optimization: Use local variables for lists, and use for loops like for i in range(256): pcost = dp[i]; if pcost == INF: continue; for j in range(M): ny = nxt[i][j]; candidate = pcost + sqdiff[ny]; if candidate < newdp[ny]: newdp[ny] = candidate.
We can also unroll? Not needed.
Potential issue: Codebook may contain duplicate values? Possibly, but that would cause redundant updates. It's fine.
Now test with sample.
We'll code.
Also note: The input format: after N M, there are M lines with one integer each, then N lines with one integer each. Reading all ints is fine.
Edge Cases: N=0? But constraints N>=1, so not needed.
Now let's code.
Potential pitfalls: Use of large INF; answer fits within int? Possibly up to 20000*65025=1,300,500,000 which fits in 32-bit signed but Python int unlimited.
Now let's write final solution.
One more improvement: Because we need min over dp after all steps, we compute ans = min(dp) at end.
Now let's write final solution.
But we must be careful about reading input: The dataset ends with "0 0". After reading N, M, if both zero, break.
Implementation:
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
out = []
INF = 10**18
while True:
N = int(next(it))
M = int(next(it))
if N == 0 and M == 0:
break
C = [int(next(it)) for _ in range(M)]
X = [int(next(it)) for _ in range(N)]
# Precompute next state: nxt[prev][code_index] = clamp(prev + C[code_index])
# We'll store as list of lists of ints.
nxt = [[0]*M for _ in range(256)]
for prev in range(256):
for idx, c in enumerate(C):
v = prev + c
if v < 0:
v = 0
elif v > 255:
v = 255
nxt[prev][idx] = v
dp = [INF]*256
dp[128] = 0
for x in X:
# Precompute squared differences for all y
sqdiff = [(x - y)*(x - y) for y in range(256)] # list comprehension
newdp = [INF]*256
# Loop over prev states
for prev in range(256):
pcost = dp[prev]
if pcost == INF:
continue
# For each code
# Possibly use local reference to nxt_prev = nxt[prev] to avoid double indexing
nxt_prev = nxt[prev]
for idx in range(M):
ny = nxt_prev[idx]
cand = pcost + sqdiff[ny]
# update newdp[ny]
if cand < newdp[ny]:
newdp[ny] = cand
dp = newdp
ans = min(dp)
out.append(str(ans))
sys.stdout.write("\n".join(out))
That should work.
Now test on sample:
I'll simulate quickly.
First dataset: N=2 M=7 C=[4,2,1,0,-1,-2,-4] X=[131,137]
Initialize dp[128]=0.
Step1 x=131:
sqdiff[y] = (131-y)^2
Precompute.
For prev=128, pcost=0.
nxt[128]: +4 -> 132; +2 ->130; +1->129; 0->128; -1->127; -2->126; -4->124
candidates:
ny=132 cost 0+(131-132)^2=1 -> newdp[132]=1
ny=130 cost 0+(131-130)^2=1 -> newdp[130]=1
ny=129 cost 0+(131-129)^2=4 -> newdp[129]=4
ny=128 cost 0+(131-128)^2=9 -> newdp[128]=9
ny=127 cost 0+(131-127)^2=16 -> newdp[127]=16
ny=126 cost 0+(131-126)^2=25 -> newdp[126]=25
ny=124 cost 0+(131-124)^2=49 -> newdp[124]=49
No other prev.
dp after step1: these values.
Step2 x=137:
For each prev, compute.
We expect optimal path: from prev=132 (+4 gives 136) cost = 1 + (137-136)^2=2 -> y=136 cost 2. Or from prev=130 (+? maybe 4 gives 134 but cost? Not lower).
Our DP will compute min. At end min dp likely 2.
Second dataset: will produce 8.
Third dataset: 10 values; codebook is symmetric; but expected output 0. Might be because signal can be reconstructed exactly? Possibly.
Our DP should yield correct.
Now complexity: 256*M per step = 4096 per step. For N=20000, 81.92M loops. Each inner loop: few lookups and additions and comparison. In CPython, 80M loops may be borderline (~2-3 seconds maybe). But we can micro-opt further:
- Use arrays from 'array' module? Not necessary.
- Use Python's built-in min? Not.
- Use for idx, ny in enumerate(nxt_prev) to avoid range(M) and index? Might be similar.
Another trick: Since M is at most 16, we can unroll the inner loop manually? Not possible generically.
But we can precompute for each prev the list of possible next states (unique? but duplicates may arise if two different c give same y, but we can combine? Actually we can keep minimal cost for each y from a given prev, but since we compute min across all c, we can just compute candidate for each c and update. Duplicate y from same prev via different c? Could happen if c values produce same y after clamping; but that's okay, we compute min. So not needed to combine.
Could we use DP with BFS? Not.
Perhaps we can reduce state space by noticing that the codebook values are small? Not necessarily, they can be up to 255. But still.
But I recall a known problem: "DPCM" from some contest (maybe ACM). The typical solution uses DP with 256 states.
Now let's consider memory and reading: Using sys.stdin.buffer.read().split() reads all integers at once, which is fine.
Potential improvement: For sqdiff, we compute (x-y)^2 for all y each step. That's 256 squares per step, i.e., 5 million squares for N=20000, that's fine.
But we could also compute candidate on the fly: diff = x - ny; cand = pcost + diff*diff. But then we compute diff each time, but that's also fine.
But precomputing sqdiff may be beneficial because it reduces repeated diff calculation for same ny from different prevs. Since each ny appears many times (maybe many prevs map to same ny), precomputing saves square computations. In our loop, we compute cand = pcost + sqdiff[ny]; that's one addition plus lookup. Without sqdiff, we would compute diff = x - ny; diff*diff each time. Since each inner iteration we compute diff, that's extra subtraction and multiplication. So precomputing is good.
Alternatively, we could compute sqdiff as list of 256 ints, and maybe use local variable.
Now, we also have nxt precomputed, which is good.
Now, we can attempt to reduce loops by only iterating over reachable states. At start only 128 reachable; after each step, reachable states might be limited? Actually given any codebook with positive and negative values, after a few steps all 256 states become reachable. But maybe some codebooks are limited: e.g., if codebook only contains 0, then only state 128 reachable. But worst-case likely all states reachable. So reachable states may quickly become all 256. So we can't skip many.
But maybe we can prune by noting that dp values can be large, but we still need to iterate.
But 80M loops in Python is doable under 2 sec? Let's test mental: In Python, 100 million simple integer operations (like a loop with a few operations) can take ~5 seconds in CPython, but PyPy JIT can be faster. On typical online judges (like AtCoder, Codeforces), Python 3 might handle ~100 million operations if optimized, but borderline. However M=16, 256*16=4096 per step. For N=20000 => 81.92M inner updates. Each update: array lookups and addition and comparison and assignment. That could be around 0.2-0.3 microseconds per operation? Actually CPython can do about 50 million simple operations per second? Not exactly; a simple loop like for i in range(100000000): pass takes about 5 seconds on CPython? Actually time python -c "for i in range(100000000): pass" -> around 5-6 seconds. So 100 million empty loop iterations is ~5 sec. With more work inside, it would be slower. So 80 million with some work might take >10 seconds. That's too slow.
But PyPy JIT can be much faster: For loop with arithmetic, PyPy might handle 100 million in a couple seconds. Many judges use PyPy for Python. So we should aim to be efficient.
We could attempt to reduce the constant factor.
Alternative approach: Use DP with BFS-like but maybe we can compute transitions more efficiently using convolution? Not likely.
Observation: The transition is: newdp[y] = min_{prev, c: clamp(prev+c)=y} (dp[prev] + (x - y)^2). Since (x - y)^2 does not depend on prev, we can rewrite:
newdp[y] = (x - y)^2 + min_{prev, c: clamp(prev+c)=y} dp[prev].
But the min over prev and c such that clamp(prev+c)=y. This is like: For each y, consider all prev such that there exists c with clamp(prev+c)=y. That is: y = clamp(prev + c). So for each c, prev = y - c, but with clamping complications: If y is at boundary 0 or 255, there could be multiple prev that map to y due to clamping. Specifically:
- If y = 0, then any prev such that prev + c <= 0 will clamp to 0. So prev <= -c. Similarly, if y = 255, any prev >= 255 - c will clamp to 255.
- For y in 1..254, only prev = y - c (if 0 <= prev <= 255) will map exactly; but if y - c is out of [0,255], then that c cannot produce y without clamping? Actually if prev + c > 255, clamp to 255, not to y unless y=255. So for y in 1..254, only those prev where prev = y - c and 0 <= prev <= 255 produce y. Also if clamping occurs, y would be 0 or 255, not interior. So for interior y, the condition is simply prev = y - c, provided 0 <= y - c <= 255. So for each y, the possible (prev, c) pairs are: For each c, if y is interior, check if prev = y - c is in [0,255]; if so, then that (prev,c) yields y. Additionally, if y = 0, for each c, any prev such that prev + c <= 0 yields y. But prev is between 0 and 255, so prev <= -c. Since c can be negative or positive. Similarly for y=255, prev >= 255 - c.
Thus we could compute newdp[y] efficiently by scanning over c and taking min of dp[prev] over a range if y is boundary. But that might be more complex. However we could handle it by considering that for interior y, the transition is simply: newdp[y] = (x-y)^2 + min_{c} dp[y - c] for those c where y - c in [0,255]. That is a kind of convolution-like min over shifts. For boundary y, we also need to consider contributions from prev that are clamped. But we can also treat clamping by considering that for each c, the mapping from prev to y is monotonic: For a fixed c, the function f(prev) = clamp(prev + c) is non-decreasing in prev. So the preimage of y is an interval (maybe a single point). Indeed:
- If c >= 0: then f(prev) = 0 for prev <= -c; f(prev) = prev + c for -c < prev < 255 - c; and f(prev)=255 for prev >= 255 - c.
- If c < 0: similar: f(prev) = 0 for prev <= -c? Actually if c is negative, say c=-5, then prev + c can be negative for small prev. f(prev)=0 for prev <= -c? Let's compute: For c negative, -c positive. Condition prev + c <= 0 => prev <= -c. So yes, f(prev)=0 for prev <= -c. For prev in [-c+1, 255 - c -1? Actually need to check upper bound: f(prev)=prev + c for 0 <= prev + c <=255, i.e., -c <= prev <= 255 - c. And f(prev)=255 for prev >= 255 - c.
Thus for each c, the mapping partitions prev into three intervals: low (clamp to 0), middle (exact addition), high (clamp to 255). For each y, the preimage is:
- If y = 0: it's the low interval: prev <= -c (if that interval is non-empty).
- If y = 255: it's the high interval: prev >= 255 - c.
- For 1 <= y <= 254: if y is within the middle range, i.e., y satisfies that there exists prev such that prev + c = y and 0 <= prev <= 255, which implies y - c in [0,255]. And then the preimage is exactly the single prev = y - c, but only if that prev is not also in low/high? Actually if prev is such that prev + c = y, and also y is not 0 or 255, then prev must be in ( -c, 255-c ) because if prev = -c exactly then prev + c = 0, not y>0. So yes it's a single point.
Thus for interior y, the transition is simple: newdp[y] = (x-y)^2 + min_{c: 0 <= y-c <= 255} dp[y-c]. For boundary y=0 and y=255, we also need to consider contributions from low and high intervals, which involve min of dp over ranges.
This could be optimized using segment trees or sliding windows to compute min over ranges for each c? Since M <= 16, we could for each c, precompute prefix minima and suffix minima to answer min over prev <= threshold and prev >= threshold quickly. But we need the min over all c combined. However we can compute for each y the min over c of either dp[y-c] (if interior) or min over dp[prev] for prev <= -c (for y=0) or prev >= 255 - c (for y=255). Since M is small, we can compute these minima by scanning all c and for boundaries we need to compute the min over ranges. To compute min over prev <= threshold, we can precompute prefix minima of dp array (min from 0 to i) and suffix minima (min from i to 255). Then for each c, for y=0, the candidate from that c is prefix_min[-c] (if -c >= 0). Actually careful: for y=0, low interval is prev <= -c. But prev is between 0 and 255. If -c < 0, then condition prev <= negative number is impossible because prev >=0, so only if -c >=0 then we have interval [0, -c]. But what if -c > 255? Since c can be negative large? But c is between -255 and 255. So -c can be up to 255. If -c >= 255, then interval is all prev [0,255]. But -c >=255 means c <= -255. Since codebook values may be -255, it's possible. Then interval is all. So we need min over dp[0..max(0, min(255, -c))]? Actually we need prev <= -c. Since prev max is 255, the effective set is prev in [0, min(255, -c)] if -c >=0. If -c >=255, then all prev (0..255) are included. Similarly for y=255: high interval is prev >= 255-c. 255-c might be >255? If c<0, 255-c >255, then condition prev >= >255 impossible. If 255-c <=0, then all prev included. So we need suffix min from max(0, 255-c) to 255.
Thus we can compute for each step:
- Compute prefix_min array: pref[i] = min_{0<=j<=i} dp[j] for i=0..255.
- Compute suffix_min array: suff[i] = min_{j=i..255} dp[j].
Then for each y, we can compute min_{c} of appropriate value:
Case y = 0:
- For each c, if -c >= 0: candidate = pref[min(255, -c)] (since prev <= -c, and prev max 255). Actually need min over prev in [0, floor] where floor = min(255, -c) because if -c > 255, then floor = 255. So candidate = pref[floor].
- If -c < 0, then no prev satisfies prev <= -c because prev>=0 > -c, so that c does not contribute to y=0? Wait: For y=0, low interval is prev such that prev + c <= 0 => prev <= -c. If -c < 0, then condition is prev <= negative number, but prev is non-negative, so no prev satisfy. So that c does not give y=0. So we ignore such c.
- So min over c of pref[floor] yields best dp[prev] for some prev that maps to y=0 via clamping.
Case y = 255:
- For each c, if 255 - c <= 255: Actually condition prev >= 255 - c, with prev <= 255. So effective start = max(0, 255 - c). If 255 - c > 255 (i.e., c < 0 and |c| large? 255 - c > 255 => -c > 0 => c < 0, then 255 - c >255, so start >255, impossible) then no prev. Also if 255 - c <= 0, then start =0, meaning all prev? Actually if 255 - c <= 0, then condition is prev >= some number <=0, so all prev >=0 satisfy, i.e., whole range. So candidate = suff[max(0, 255 - c)]? Actually suffix min from start to 255. So candidate = suff[max(0, 255 - c)].
- But we also need to consider if 255 - c < 0, then start =0, and candidate = suff[0] which is overall min of dp.
- So for each c, if 255 - c <= 255 (always true because c can be -255..255, 255 - c ranges from 0 to 510) but we must ensure that start <=255: start = max(0, 255 - c). If 255 - c > 255, then start >255, no prev. So only if 255 - c <= 255 i.e., c >= 0, then start = 255 - c (since c>=0 => 255-c in [0,255]). If c < 0, then 255 - c > 255, start >255, so no prev. But wait, is that correct? For c negative, say c = -1, then prev + (-1) >= 255 => prev >= 256? Actually clamp to 255 occurs when prev + c >= 255, i.e., prev >= 255 - c. For c=-1, 255 - (-1)=256, so prev >=256, but prev max is 255, so no prev; thus negative c cannot produce y=255 because adding a negative reduces value, so cannot reach 255 unless prev already 255? But if prev=255 and c=-1, then 255 + (-1)=254, not 255. So indeed negative c cannot produce y=255 via clamping? Actually if prev=255 and c=0, then y=255. If c negative, adding reduces, so you can't exceed 255. The only way to get y=255 is when prev + c >= 255, which for c negative is impossible because max prev is 255, 255 + negative < 255, except if c is positive. So for y=255, only c >= 0 contribute. And if c positive large, then 255 - c may be small or negative; if 255 - c <=0, then any prev >=0 satisfies? Actually if c >= 255, then 255 - c <=0, condition prev >= negative number, so all prev (0..255) satisfy? Let's test: c=255, prev + 255 >=255 for all prev>=0, so indeed all prev map to y=255 due to clamping? Actually if prev+255 >=255 => prev>=0, so always true, but clamp: if prev+255 >255, then y=255, if exactly 255? Actually if prev+255 >255 for prev>0; for prev=0, 0+255=255 exactly, y=255. So all prev map to 255. So yes, for c>=255, the high interval includes all prev. So our suffix min with start=0 (if 255-c <=0) captures that.
Thus for y=255, candidate from each c is:
if 255 - c <= 255 (i.e., c >=0) then start = max(0, 255 - c) and candidate = suff[start].
If c<0, then no contribution.
But also there is the middle interval? For interior y, we only consider the exact mapping. But for y=0 and y=255, there are also contributions from the exact mapping when y-c is within [0,255] and also that resulting y is exactly 0 or 255? Actually if y=0 and we have a c such that y-c is within [0,255], that would imply prev = 0 - c = -c, and we need 0 <= -c <=255. That prev yields y = clamp(prev + c) = clamp(-c + c) = clamp(0) = 0, so that is also a valid mapping. But note that this prev also falls into the low interval? If prev = -c, then prev <= -c holds, so it's included in the low interval as well (since low interval is prev <= -c). However, the exact mapping point is actually the boundary of the low interval. Since we are taking min over the entire low interval (including the endpoint), we will capture that dp value if it's the min. But need to ensure that the exact mapping point is considered. In low interval, we consider all prev <= -c. That includes prev = -c. So the exact mapping is included. So for y=0, using pref[min(255, -c)] gives min over all prev from 0 to floor, which includes the exact point. So it's correct.
Similarly for y=255, suffix min from start includes exact point if start = 255 - c (which is exactly the prev that maps exactly to 255 when no clamp? Actually if prev = 255 - c, then prev + c = 255, so y=255. That's included in suffix interval prev >= 255 - c, which includes that point. So good.
Now for interior y (1..254), we need to consider only the exact mapping from prev = y - c, provided 0 <= y - c <= 255. There is no interval because clamping does not affect interior values; only exact addition yields that y. So candidate = dp[y - c] for each c where y - c in [0,255].
Thus newdp[y] = (x - y)^2 + min( min_{c: 0<=y-c<=255} dp[y-c], (if y=0) also min_{c: -c >=0} pref[min(255, -c)], (if y=255) also min_{c: c>=0} suff[max(0, 255-c)] ).
But note: For y=0, we also have contributions from exact mapping when 0 <= -c <= 255 (i.e., c <=0 and -c between 0 and 255). This is included in the low interval min because pref includes prev = -c. So we don't need separate.
Similarly for y=255, exact mapping when 0 <= 255 - c <= 255 (i.e., c between 0 and 255) is included in suffix min.
Thus algorithm per step:
Given dp[0..255] from previous step.
Precompute prefix minima: pref[i] = min(dp[0..i]).
Suffix minima: suff[i] = min(dp[i..255]).
Then for each y from 0 to 255:
- base = (x - y)^2.
- best = INF
- For interior y (1..254):
For each c in C:
prev = y - c
if 0 <= prev <= 255:
candidate = dp[prev]
best = min(best, candidate)
- For y = 0:
For each c in C:
if -c >= 0: // i.e., c <= 0
floor = min(255, -c)
candidate = pref[floor] // min dp[0..floor]
best = min(best, candidate)
// also consider the exact mapping? Already covered because if -c between 0 and 255, then floor = -c and pref[floor] includes dp[-c].
// Additionally, what about c positive? For c>0, -c<0, so no low interval. But could exact mapping produce y=0? If y=0 and c>0, then prev = -c <0, invalid. So no.
- For y = 255:
For each c in C:
if c >= 0: // because condition prev >= 255-c only applies when c>=0? Actually we need to check if there exists prev such that prev + c >=255. For c negative, no. So only c>=0.
start = max(0, 255 - c)
candidate = suff[start]
best = min(best, candidate)
But wait, for y=255, if c is positive and large such that 255 - c <=0, start=0, suff[0] is overall min, which includes all prev. That's correct.
Now is this enough? Let's also consider the middle interval for boundary? For y=0, if c is such that the middle interval includes y=0? That would require that there exists prev such that prev + c = 0 and prev in [0,255], i.e., prev = -c, 0<= -c <=255. That's exactly covered by low interval because prev <= -c includes that point. So fine.
Thus we can compute newdp[y] efficiently.
But we need to be careful: The transition for interior y does not include clamping contributions because clamping only yields 0 or 255. So interior y only come from exact addition. So the above covers all cases.
Now complexity per step: For interior y (254 values) we iterate over M codes (<=16) => ~25416=4064 operations. For y=0 and y=255 we also iterate over M each, total ~32. So overall per step ~4096 operations, same as before! So no improvement in asymptotic. But we might reduce constant factor because we avoid iterating over prev (256) and instead iterate over y and c, which is same order. Actually original method iterated prev (256) and c (M) => 256M. New method iterates y (256) and c (M) => also 256*M. So similar.
But there is a subtle difference: In original method, we loop over prev and for each c compute ny = clamp(prev+c) and update newdp[ny]. That involves writing to newdp[ny] and checking min. In the new method, we compute for each y the min over c (and possibly prefix/suffix). That also involves reading dp and prefix/suffix arrays. The number of operations is similar.
However, the new method could be more efficient because it doesn't involve the clamp function (which is replaced by conditions). But we precomputed nxt, so clamp is just array lookup. So both are similar.
But perhaps we can further optimize by noticing that for interior y, we need min over c of dp[y-c] where y-c in [0,255]. This is like a convolution of dp with a filter (min over shifted copies). Since M is small, we can compute for each y the min by iterating c. That's still 256*16.
Given that, the simple DP with 256*M per step is fine. But maybe we can do even better using monotonic queue? Not needed.
But we should consider that the problem constraints include N up to 20000, but also M up to 16. So 2561620000 = 81.92M. This is likely acceptable in C++ but may be borderline in Python. However, many Python solutions for similar problems (like DP with 256 states) pass with such constraints. Let's search memory: I've seen UVA 526 (maybe) or similar. Possibly it's from ACM/ICPC Japan. Python might be okay with optimization.
I'll stick with the simple DP, but with micro-optimizations: precompute nxt, precompute sqdiff, use local variables, avoid function calls, use list comprehension for sqdiff. Also we can use Python's built-in min over a list? Not.
We could also implement using arrays from 'array' or 'numpy', but not allowed in standard judges.
Alternatively, we can reduce state space to only reachable states each step, but as argued, after few steps all states may become reachable. But maybe we can use set of states where dp is not INF. At each step, we can store a dictionary of state->cost for those that are not INF. However number of states could be 256 anyway. So using list of size 256 is fine.
But there is a nuance: When we update newdp[ny] from dp[prev], we may update the same ny multiple times. That's okay.
Now, let's test with sample.
But before finalizing, consider whether the DP recurrence is correct: y_n = clamp(y_{n-1} + C[kn]). This is exactly what we did.
Now, check for potential overflow: dp values up to about 1.3e9, but we use INF=10**18, safe.
Now, test with sample manually. Should output:
2
8
0
325125
65026
The sample includes a dataset: 10 7 ... output 0.
Our code should produce that.
But we must check reading: In sample input, after first dataset, there is blank line? But reading ints ignores whitespace.
Now, about the third dataset: 10 7 with codebook -4 -2 -1 0 1 2 4 and X: 132 134 135 134 132 128 124 122 121 122. The output is 0, meaning we can exactly reproduce. Let's test quickly: Starting y0=128, we need to get y1=132 (diff +4), y2=134 (+2), y3=135 (+1), y4=134 (-1), y5=132 (-2), y6=128 (-4), y7=124 (-4), y8=122 (-2), y9=121 (-1), y10=122 (+1). These diffs are all in codebook. So yes.
Our DP should find 0.
Now, performance: We'll implement with the simple DP (prev->next) as it's straightforward.
But we need to be careful about reading large input: using sys.stdin.buffer.read() is fast.
Now, could there be any tricky case: Codebook may contain values that cause same ny for many prev? That's fine.
Now, I'll implement final solution accordingly.
But wait, what about memory and time for precomputing nxt: 256 * M = up to 4096 entries, trivial.
Now, for Python, we may want to use for loops but avoid attribute lookups. For instance, inside the step loop, we do:
nxt = precomputed_nxt
dp = previous_dp
sqdiff = precomputed list
We'll use local references: nxt_local = nxt; newdp_local = newdp; dp_local = dp; M_local = M; C_indices = range(M) perhaps.
But we can also use enumerate.
Also, we can precompute for each prev a list of possible ny (maybe unique). Since M small, not necessary.
We could also sort C? Not needed.
Now, let's code and test.
But let's also think about potential improvement: Since dp[prev] is INF for many states initially, but after first step, the number of states reachable may be at most M (if M < 256). Actually after first step from y0=128, reachable states are clamp(128 + C[j]) for each j. So at most M states. After second step, each of those can branch to at most M states, so at most M^2 states? But due to clamping and overlapping, number could increase but maybe still limited? Actually maximum distinct states is bounded by 256, so worst-case full. But early steps could have fewer states, but we still iterate over all 256 prev states checking INF. That's fine.
We could maintain a list of active states (those with dp < INF) and only iterate those. That would reduce operations if many states unreachable. However, after a few steps, the set may become all 256. In worst-case codebook with both positive and negative values, after a few steps, all states become reachable? Let's think: If codebook contains 1 and -1, from 128 we can reach any integer between 0 and 255 eventually? Starting from 128, with +1 and -1, we can reach any value? Not exactly: if you can increment and decrement by 1, you can reach any integer between 0 and 255, but need enough steps. After N steps, reachable set is [max(0, 128 - N), min(255, 128 + N)] essentially. So for N=128, you can reach 0 or 255. So after many steps, almost all states become reachable. For N up to 20000, eventually all 256 are reachable. So active set becomes full. So overhead of maintaining a list may not help much.
But to be safe, we can still attempt to use active states to reduce early steps but it's negligible.
Given the constraints, simple DP should pass.
Let's test with Python (simulate a large dataset mentally). Probably okay.
But I want to ensure we don't hit time limit. I recall that UVA 526 "String Distance and Transform Process" is something else. But this problem is from "AIZU ONLINE JUDGE" maybe? Possibly problem "DPCM". I've seen similar problem. The intended solution is DP with 256 states, and it's accepted in C. For Python, might be okay with optimization.
Alternatively, we can compress state space using difference? No.
I'll implement the DP as described.
One more micro-optim: Instead of using list comprehension for sqdiff each step, we could compute on the fly: diff = x - ny; cost = pcost + diffdiff. This avoids building a list of 256 ints. But building a list of 256 ints is cheap (256 assignments) vs 25616=4096 calculations of diff. Actually diff calculation per iteration is done anyway. But if we precompute sqdiff, we do 256 squares (multiplications) per step, and then in inner loop we do addition and lookup. Without precompute, we do 4096 diff subtractions and multiplications. Which is more? 256 squares = 256 multiplications; 4096 diff squares = 4096 multiplications. So precompute reduces multiplications. Also precompute reduces overhead of computing diff each time. So precompute is better.
But we could also compute sqdiff on the fly using a lambda? No.
So precompute sqdiff.
Now, code.
I'll write:
def solve():
import sys
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
out = []
INF = 10**18
while True:
try:
N = next(it)
M = next(it)
except StopIteration:
break
if N == 0 and M == 0:
break
C = [next(it) for _ in range(M)]
X = [next(it) for _ in range(N)]
# Precompute nxt
nxt = [[0]*M for _ in range(256)]
for p in range(256):
p_nxt = nxt[p]
for i, c in enumerate(C):
v = p + c
if v < 0:
v = 0
elif v > 255:
v = 255
p_nxt[i] = v
dp = [INF]*256
dp[128] = 0
for x in X:
# sqdiff
sq = [0]*256
# could compute using loop for y
# but we can compute using list comprehension
# To avoid Python overhead, manual loop may be faster? We'll test.
# Use for y in range(256): sq[y] = (x - y)*(x - y)
# But list comprehension is fine.
# We'll use list comprehension.
sqdiff = [(x - y)*(x - y) for y in range(256)]
newdp = [INF]*256
# iterate over prev
for prev in range(256):
pcost = dp[prev]
if pcost == INF:
continue
# local references
nxt_prev = nxt[prev]
# unroll maybe? just loop
for idx in range(M):
ny = nxt_prev[idx]
cand = pcost + sqdiff[ny]
if cand < newdp[ny]:
newdp[ny] = cand
dp = newdp
ans = min(dp)
out.append(str(ans))
sys.stdout.write("\n".join(out))
Now, but there is a potential bug: The codebook values can be any integer, including large ones like 255 or -255. nxt precomputation with clamp is correct.
Now, test with sample.
Let's simulate quickly:
Dataset 1: N=2 M=7 C as given, X[131,137].
After step1, dp[132]=1, etc. After step2, min should be 2.
But we should ensure that we handle negative numbers properly.
Now, is there any nuance about rounding? The problem says "yn is rounded to 0 if the value is less than 0 by addition, and to 255 if the value is greater than 255." That's clamp.
Now, we need to output the minimum sum of squares.
Edge case: M might be 0? But M >=1.
Now, I'll think about potential time: 81.92M inner loop iterations. Each iteration does: array lookups (nxt_prev[idx]), sqdiff[ny] lookup, addition, compare, assignment if less. In CPython, each iteration may take about 50-100 ns? Actually typical CPython can do about 30-50 million simple operations per second? Let's estimate: A loop with a few operations can do about 30 million iterations per second? I'm not sure. But 80 million may take 2-3 seconds. However plus overhead of outer loops and data reading. Could be 4 seconds. Many judges have time limit 2-3 sec. Might be borderline.
We can try to reduce the inner loop by using Python's built-in min over a small list? Not.
Maybe we can restructure to loop over next states rather than previous states. That is, for each y, we compute min over prev and c. That's same complexity.
But we can also use vectorized operations with numpy, but not allowed usually.
Alternatively, we can use BFS-like approach with only states that have finite dp, but as argued, after few steps it's full.
But maybe we can compress state space because y values are only 256, we can use dynamic programming with "relaxation" using that transition is like dp_next[y] = (x-y)^2 + min_{c} dp[prev] where prev depends on y. Actually we derived formula: for interior y, dp_next[y] = (x-y)^2 + min_{c} dp[y - c] (if y-c in range). That's a min over M values, which can be computed quickly if we have dp array. That is similar complexity: 256*M.
But maybe we can compute this min using convolution with min instead of sum, but M small.
Another micro-optim: Since sqdiff depends on y, we can combine: newdp[y] = sqdiff[y] + best[y], where best[y] = min_{c: valid} dp[prev] for that y. For interior y, best[y] = min_{c in