Go: package main

import (
	"bufio"
	_ "container/heap"
	"fmt"
	"os"
	_ "sort"
	"strconv"
)

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	return a / gcd(a, b) * b
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

// Main
const MOD = int(1e+9) + 7
const INF = 1 << 60

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	defer wtr.Flush()
	for true {
		N, M := sc.nextInt(), sc.nextInt()
		if N == 0 && M == 0 {
			break
		}
		C := sc.nextIntSlice(M)
		X := sc.nextIntSlice(N)
		dp := make([][256]int, N+1)
		for i := 0; i < N+1; i++ {
			for j := 0; j < 256; j++ {
				dp[i][j] = INF
			}
		}
		dp[0][128] = 0
		for i := 0; i < N; i++ {
			for j := 0; j < 256; j++ {
				if dp[i][j] == INF {
					continue
				}
				for k := 0; k < M; k++ {
					nex := j + C[k]
					if nex < 0 {
						nex = 0
					}
					if nex > 255 {
						nex = 255
					}
					dp[i+1][nex] = min(dp[i+1][nex], dp[i][j]+pow(X[i]-nex, 2))
				}
			}
		}
		ans := INF
		for i := 0; i < 256; i++ {
			ans = min(ans, dp[N][i])
		}
		fmt.Fprintln(wtr, ans)
	}
}

Python: import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []
    M = 256
    sq = [i**2 for i in range(M)]
    nkss = [[sq[abs(x-nk)] for nk in range(M)] for x in range(M)]
    ML = list(range(M))

    def f(m, n):
        cs = [I() for _ in range(m)]
        xs = [I() for _ in range(n)]
        ml = list(range(m))
        d = [inf] * M
        nd = [inf] * M
        d[128] = 0
        ckl = list(map(lambda x: (max(min(x[0]+x[1], 255), 0), x[1]), (itertools.product(cs, ML))))
        for i in range(n):
            nd = [inf] * M
            for nk,k in ckl:
                if nd[nk] > d[k]:
                    nd[nk] = d[k]
            d = [nn + kk for nn,kk in zip(nd, nkss[xs[i]])]
        return min(d)

    while True:
        n,m = LI()
        if m == 0 and n == 0:
            break
        rr.append(f(m,n))

    return '\n'.join(map(str,rr))




print(main())

Python: import sys
from itertools import product
input = sys.stdin.readline


def inpl():
    return list(map(int, input().split()))


def solve(N, M):
    C = [int(input()) for _ in range(M)]
    X = [int(input()) for _ in range(N)]

    ret = [float('inf')] * 256
    ret[128] = 0
    cor = set((max(min(i + c, 255), 0), i) for c, i in product(C, list(range(256))))
    xt = tuple(tuple((x - t)**2 for x in range(256)) for t in range(256))
    for x in X:
        tmp = [float('inf')] * 256
        xt_now = xt[x]
        for t, i in cor:
            v = ret[i]
            if v + xt_now[t] < tmp[t]:
                tmp[t] = v + xt_now[t]
        ret = tmp[:]

    return min(ret)


def main():
    ans = []
    while True:
        N, M = inpl()
        if N == M == 0:
            break
        ans.append(solve(N, M))
    for a in ans:
        print(a)
    return


main()

Python: # -*- coding: utf-8 -*-
def inpl(): return list(map(int, input().split()))

def main():
    N, M = inpl()
    INF = 10**9
    while N:
        C = [int(input()) for _ in range(M)]
        X = [int(input()) for _ in range(N)]
        Y = [[INF]*256 for i in range(N+1)]
    
        for i in range(256):
            Y[0][i] = 0
    
        for i, x in enumerate(X):
            for j in range(256):
                if Y[i][j] == INF:
                    continue
                for c in C:
                    k = min(255, max(0, j+c))
                    Y[i+1][k] = min(Y[i+1][k], Y[i][j] + (x - k)**2)
    
        print(min(Y[-1]))
        N, M = inpl()

if __name__ == "__main__":
    main()

Python: #先人の方々の知恵を借りて、workの評価式と<(x-x_r)^2>のテーブルを使ってみる
#clst、xlst、tableをタプル化してパフォーマンスを向上
#比較的重いtb1へのアクセスをsetにする


def main():
    inf=float("inf")

    while 1 :
        n,m=map(int,input().split())
        if (n,m)==(0,0) : break
        clst=tuple(int(input()) for _ in range(m))
        xlst=tuple(int(input()) for _ in range(n))

        #tb1=tuple(tuple(255 if i+work>255 else 0 if i+work<0 else i+work for work in clst) for i in range(256))
        tb1=set((max(0,min(255,i+work)),i) for work in clst for i in range(256))
        #ij成分が(i-j)^2に対応する行列
        tb2=tuple(tuple((i-j)**2 for j in range(256)) for i in range(256))

        dp_new=[inf]*256
        dp_new[128]=0
        for val in xlst:
            dp_old=dp_new[:]
            dp_new=[inf]*256
            xlst_tb=tb2[val]
            for j,i in tb1:
                error=dp_old[i]+xlst_tb[j]
                if error<dp_new[j] :
                    dp_new[j]=error
        
        print(min(dp_new))

main()

Python: def resolve():
    import sys
    input = lambda: sys.stdin.readline().rstrip() 
    INF = 10**12

    sq_diff = tuple(tuple((i-j)**2 for j in range(256)) for i in range(256))
    while True:
        N, M = map(int, input().split())
        C = tuple(int(input()) for _ in range(M))
        x = tuple(int(input()) for _ in range(N))
        if N==M==0:
            break
        else:
            normalize = tuple(tuple(255 if i+c>255 else 0 if i+c<0
                    else i+c for c in C) for i in range(256))
            dp_cur = [INF]*256
            dp_cur[128] = 0
            dp_next = [INF]*256
            for i in x:
                sq_diff_x = sq_diff[i]
                for j, cost_cur in enumerate(dp_cur):
                    normalize_j = normalize[j]
                    for l in normalize_j:
                        cost_next = cost_cur + sq_diff_x[l]
                        if cost_next < dp_next[l]:
                            dp_next[l] = cost_next

                dp_cur = dp_next[:]
                dp_next = [INF]*256

            print(min(dp_cur))

if __name__ == '__main__':
    resolve()