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 = 998244353

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 = []

    while True:
        n,m = LI()
        if n == 0 and m == 0:
            break

        cs = [I() for _ in range(m)]
        xs = [I() for _ in range(n)]
        d = collections.defaultdict(int)
        d[128] = 0
        for x in xs:
            n = collections.defaultdict(lambda: inf)
            for k,v in d.items():
                for c in cs:
                    nk = max(min(k+c,255),0)
                    if n[nk] > v + (x-nk) ** 2:
                        n[nk] = v + (x-nk) ** 2
            d = n

        rr.append(min(d.values()))


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


print(main())

Python: # import copy
# answers = []

from sys import stdin
input = stdin
def solve():
    while True:
        n, m = map(int,input.readline().split())
        if n == 0 and m == 0:
            break
        # c = []
        # x = [128]
        INF = float('inf')
        # for i in range(m):
        #     c.append(int(input()))
        c = tuple(int(input.readline()) for i in range(m))
        tb1 = tuple(tuple((i-j)**2 for i in range(256)) for j in range(256))
        tb2 = tuple(tuple(255 if i+ci>255 else 0 if i+ci<0 else i+ci for ci in c) for i in range(256))
        # for j in range(n):
        #     x.append(int(input()))
        # dp = [[INF]*(256) for _ in range(n+1)] #dp[i][j]は信号の大きさj入力した時のi番目の信号との二乗誤差の合計
        dp1 = [INF]*256
        dp2 = [INF]*256
        # prev = set([128])
        # dp[0][128] = 0
        dp1[128] = 0
        for i in range(n):
            x = int(input.readline())
            # nexts = set([])
            # print(prev)
            tb1_x = tb1[x]
            # for j in range(256):
            for j,precost in enumerate(dp1):
                for a in tb2[j]:
                    # a = j + c[k]
                    # a = tb2[j][k]
                    # nexts.add(a)
                    # print(dp2[a],dp1[j] + tb1[a][x])
                    # dp[i+1][a] = min(dp[i+1][a],dp[i][j] + tb1[a][x])
                    newcost = precost+tb1_x[a]
                    if newcost<dp2[a]:
                        dp2[a] = newcost
                    # dp2[a] = min(dp2[a], dp1[j] + tb1_x[a] )
            # prev = nexts
            dp1 = dp2[:]
            dp2 = [INF]*256
        # for i in range(n+1):
        #     print(x[i],"→",*dp[i][120:256])
        print(min(dp1))
solve()
# for ans in answers:
#     print(ans)

Python: def solve():
    from sys import stdin
    INF = float('inf')
    f_i = stdin
    
    while True:
        N, M = map(int, f_i.readline().split())
        if N == 0:
            break
        
        C = tuple(int(f_i.readline()) for i in range(M))
        
        # decode table
        tbl_1 = 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))
        
        # tabale of squared difference
        tbl_2 = tuple(tuple((i - j) ** 2 for j in range(256)) \
                      for i in range(256))
        
        dp1 = [INF] * 256
        dp2 = [INF] * 256
        dp1[128] = 0
        
        for i in range(N):
            x = int(f_i.readline())
            tbl_2_x = tbl_2[x]
            for signal, pre_cost in enumerate(dp1):
                for decoded in tbl_1[signal]:
                    new_cost = pre_cost + tbl_2_x[decoded]
                    if new_cost < dp2[decoded]:
                        dp2[decoded] = new_cost
            dp1 = dp2[:]
            dp2 = [INF] * 256
        
        print(min(dp1))

solve()

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()