Problem:
Problem C:
Differential Pulse Code Modulation
差分パルス符号変調は主に音声信号を圧縮する際に用いられる圧縮手法の一つである．
音声信号は計算機上では整数列(インパルス列)として扱われる．整数列は入力信号を一定時間間隔で標本化(サンプリング)し，振幅を記録したものである．一般にこの整数列は前後の値が近いという傾向がある．これを利用し，前後の値の差分を符号化し，圧縮率を向上させるのが差分パルス符号変調である．
本問題では差分の値をあらかじめ定められた値の集合から選ぶことを考える．この値の集合をコードブックと呼ぶことにする．復号化後の音声信号
y
n
は以下の式で定められる．
y
n
=
y
n
- 1
+
C
[
k
n
]
ここで
k
n
はプログラムによって出力される出力系列，
C
[
j
]
はコードブックの
j
番目の値である．ただし
y
n
は加算によって0未満の値となった場合は0に，255より大きい値となった場合は255にそれぞれ丸められる．また，
y
0
の値は128とする．
あなたの仕事は，入力信号とコードブックが与えられたときに，元の入力信号と復号化後の出力信号との差の二乗和が最小となるように出力系列を選んで，そのときの差の二乗和を出力するプログラムを書くことである．
例えば，コードブックとして
{4, 2, 1, 0, -1, -2, -4}
という値のセットを使って
131, 137
という列を圧縮する場合，
y
0
= 128
,
y
1
= 128 + 4 = 132
,
y
2
= 132 + 4 = 136
という列に圧縮すると
二乗和が
(131 - 132)^2 + (137 - 136)^2 = 2
と最小になる．
また，同じくコードブックとして
{4, 2, 1, 0, -1, -2, -4}
という値のセットを使って
131, 123
という列を圧縮する場合，
y
0
= 128
,
y
1
= 128 + 1 = 129
,
y
2
= 129 - 4 = 125
と，先程の例とは違って
131
により近づく
+2
を採用しない方が
(131 - 129) ^ 2 + (123 - 125) ^ 2 = 8
というより小さな二乗和が得られる．
上記 2つの例は sample input の最初の 2例である．
Input
入力は複数のデータセットから構成される．各データセットの形式は次に示すとおりである．
N
M
C
1
C
2
...
C
M
x
1
x
2
...
x
N
最初の行は，入力データセットの大きさを規定する．
N
は圧縮する入力信号の長さ(サンプル数)である．
M
はコードブックに含まれる値の個数である．
N
及び
M
は1 ≤
N
≤ 20000，1
≤
M
≤ 16を満たす．
これに続く
M
行は，コードブックの記述である．
C
i
はコードブックに含まれる
i
番目の値を表す．
C
i
は-255 ≤
C
i
≤ 255を満たす．
これに続く
N
行は，入力信号の記述である．
x
i
は入力信号を表す整数列の
i
番目の値である．
x
i
は0 ≤
x
i
≤ 255を満たす．
データセットの中の入力項目は，すべて整数である．入力の終りは，空白文字1個で区切られた2個のゼロのみからなる行で表される．
Output
入力の各データセットに対して， 元の入力信号と復号化後の出力信号との差の二乗和の最小値を一行で出力せよ．
Sample Input
2 7
4
2
1
0
-1
-2
-4
131
137
2 7
4
2
1
0
-1
-2
-4
131
123
10 7
-4
-2
-1
0
1
2
4
132
134
135
134
132
128
124
122
121
122
5 1
255
0
0
0
0
0
4 1
0
255
0
255
0
0 0
Output for the Sample Input
2
8
0
325125
65026

Submitted solutions:

code_snippet: #include <iostream>
#include <vector>
#include <cmath>
#include <climits>

using namespace std;

int main(){

    while(1){
    
        int N, M;
        cin >> N >> M;
        if (N==0 && M==0) break;

        vector<int> C(M);
        vector<int> X(N);

        for (int i=0; i<M; i++) cin >> C[i];
        for (int i=0; i<N; i++) cin >> X[i];

        vector<vector<int>> dp(N+1, vector<int>(256));
        for (int i=0; i<=N; i++) {
            for (int j=0; j<256; j++){
                dp[i][j] = INT_MAX;
            }
        }
        dp[0][128] = 0;

        for (int i=0; i<N; i++){
            for (int j=0; j<256; j++){
                if (dp[i][j] == INT_MAX) continue;
                for (int k=0; k<M; k++){
                    int yn = j + C[k];
                    yn = max(yn, 0);
                    yn = min(yn, 255);
                    int error = pow(X[i]-yn, 2);
                    dp[i+1][yn] = min(dp[i+1][yn], dp[i][j]+error);
                }
            }
        }

        int ans = INT_MAX;
        for (int i=0; i<256; i++){
            ans = min(ans, dp[N][i]);
        }

        cout << ans << endl;

    }

    return 0;
}
accuracy: 1
time_ms: 510
memory_kb: 23992
final_rank: 11

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
typedef long long int ll;

#define BIG_NUM 2000000000

using namespace std;

int N,M;
int** dp;

void func(){
	int codeTable[M];

	for(int i = 0; i < M; i++){
		scanf("%d",&codeTable[i]);
	}

	int num;
	dp[0][128] = 0;

	for(int count = 1; count <= N; count++){
		scanf("%d",&num);

		for(int i = 0; i <= 255; i++){
			if(dp[count-1][i] != BIG_NUM){
				for(int k = 0; k < M; k++){
					if(i+codeTable[k] > 255){
						dp[count][255] = min(dp[count][255],dp[count-1][i]+(num-255)*(num-255));
					}else if(i+codeTable[k] < 0){
						dp[count][0]  = min(dp[count][0],dp[count-1][i]+(num)*(num));
					}else{
						dp[count][i+codeTable[k]] = min(dp[count][i+codeTable[k]],dp[count-1][i] + (num-(i+codeTable[k]))*(num-(i+codeTable[k])));
					}
				}
			}
		}
	}

	int minimum = BIG_NUM;

	for(int i = 0; i <= 255; i++){
		minimum = min(minimum,dp[N][i]);
	}

	printf("%d\n",minimum);

}

int main(){

	dp = new int*[20001];
	for(int i = 0; i <= 20000; i++){
		dp[i] = new int[256];
	}

	while(true){
		scanf("%d %d",&N,&M);
		if(N == 0 && M == 0)break;

		for(int i = 0; i <= N; i++){
			for(int k = 0; k <= 255; k++)dp[i][k] = BIG_NUM;
		}

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 350
memory_kb: 23204
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
// #include <atcoder/all>
// using namespace atcoder;
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
using Board = vector<string>;
// using mint = modint998244353;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
using vp = vector<P>;
using vvp = vector<vector<P>>;
using vb = vector<bool>;
using vvb = vector<vector<bool>>;
using vs = vector<string>;
using sl = set<ll>;
using Graph = vector<vector<ll>>;
using pq = priority_queue<ll>;
using pqg = priority_queue<ll, vector<ll>, greater<ll>>;
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define nall(a) a.begin(), a.end()
const ll INF = 1LL << 60;

int main(){
    ll n, m;
    while (cin>>n>>m, n+m) {
        vl code(m), palce(n);
        rep(i,m) cin >> code[i];
        rep(i,n) cin >> palce[i];
        vvl dp(n+1, vl(256, INF));
        dp[0][128] = 0;
        rep(i,n)rep(j,256) {
            if (dp[i][j] == INF) continue;
            rep(k,m) {
                ll y = max(0LL, min(255LL, j+code[k]));
                dp[i+1][y] = min(dp[i+1][y], dp[i][j]+(ll)pow(y-palce[i],2));
            }
        }
        ll ans = INF;
        rep(i,256) ans = min(ans, dp[n][i]);
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 580
memory_kb: 43800
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;

int main() {
    int N, M;
    int C[29], X[20009];
    long long INF = 10000000000000LL;

    while (cin >> N >> M) {
        if (N == 0 && M == 0) break;

        for (int i = 1; i <= M; i++) cin >> C[i];
        for (int i = 1; i <= N; i++) cin >> X[i];

        // dp[v][i] : i 個目まで見て y_i = v の最小コスト
        vector<vector<long long>> dp(256, vector<long long>(N + 1, INF));

        // y0 = 128 固定
        dp[128][0] = 0;

        for (int i = 1; i <= N; i++) {
            for (int p = 0; p <= 255; p++) {
                if (dp[p][i - 1] == INF) continue;
                for (int k = 1; k <= M; k++) {
                    int t = p + C[k];
                    int nxt;
                    if (t < 0) nxt = 0;
                    else if (t > 255) nxt = 255;
                    else nxt = t;
                    long long cost = dp[p][i - 1] + 1LL * (X[i] - nxt) * (X[i] - nxt);
                    if (cost < dp[nxt][i]) dp[nxt][i] = cost;
                }
            }
        }

        long long ans = INF;
        for (int v = 0; v <= 255; v++) ans = min(ans, dp[v][N]);
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 660
memory_kb: 44140
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, n) for (int i = a; i < n; i++)
using ll = long long;
using ld = long double;
using pl = pair<ll, ll>;
using vl = vector<ll>;
using vvl = vector<vl>;
const int mod = 998244353;
const ll hashh = 2147483647;

int main()
{
    while (1)
    {
        ll n, m;
        cin >> n >> m;
        if (n == 0 && m == 0)
            break;
        vl c(m), x(n);
        rep(i, 0, m) cin >> c[i];
        rep(i, 0, n) cin >> x[i];
        vvl a(n, vl(300, 1000000000));
        rep(i, 0, m)
        {
            if (128 + c[i] < 0)
            {
                a[0][0] = min(a[0][0], x[0] * x[0]);
            }
            else if (128 + c[i] > 255)
            {
                a[0][255] = min(a[0][255], (x[0] - 255) * (x[0] - 255));
            }
            else
            {
                a[0][128 + c[i]] = min(a[0][128 + c[i]], (x[0] - (128 + c[i])) * (x[0] - (128 + c[i])));
            }
        }
        rep(i, 1, n)
        {
            rep(j, 0, 256)
            {
                rep(k, 0, m)
                {
                    if (j + c[k] < 0)
                    {
                        a[i][0] = min(a[i][0], x[i] * x[i] + a[i - 1][j]);
                    }
                    else if (j + c[k] > 255)
                    {
                        a[i][255] = min(a[i][255], (x[i] - 255) * (x[i] - 255) + a[i - 1][j]);
                    }
                    else
                    {
                        a[i][j + c[k]] = min(a[i][j + c[k]], (x[i] - (j + c[k])) * (x[i] - (j + c[k])) + a[i - 1][j]);
                    }
                }
            }
        }
        ll ans = 10000000000;
        rep(i, 0, 256)
        {
            ans = min(ans, a[n - 1][i]);
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 460
memory_kb: 50816
final_rank: 13

code_snippet: #include <bits/stdc++.h>
#define ll long long
#define ld long double
using namespace std;

bool solve(){
    int n,m;
    cin >> n >> m;
    
    if(n == 0 && m == 0) return false;
    
    vector<vector<int>> dp(n+1,vector<int>(256,2e9));
    
    dp[0][128] = 0;
    
    vector<int> c(m);
    for(auto& i:c) cin >> i;
    
    int x;
    
    for(int i = 1;i <= n;i++){
        cin >> x;
        for(int j = 0;j < 256;j++){
            for(int k = 0;k < m;k++){
                int ind = max(0,min(j+c[k],255));
                
                dp[i][ind] = min(dp[i][ind],dp[i-1][j]+(x-ind)*(x-ind));
            }
        }
    }
    
    int ans = 2e9;
    
    for(int i = 0;i < 256;i++){
        ans = min(ans,dp[n][i]);
    }
    
    cout << ans << endl;
    
    return true;
}

int main(void){
    
    while(solve()) continue;
    
}
accuracy: 1
time_ms: 420
memory_kb: 23864
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;

const ll INF=1e15;

vector<vector<ll>> dp(20001, vector<ll>(256,INF));

int main() {
    int N, M;
    while(cin >> N >> M && N!=0 && M!=0){
        vector<ll> C(M), x(N);
        for(int i=0; i<M; i++){
            cin >> C[i];
        }
        for(int i=0; i<N; i++){
            cin >> x[i];
        }

        dp=vector<vector<ll>>(20001, vector<ll>(256,INF));
        dp[0][128]=0;
        for(int i=0; i<N; i++){
            for(int j=0; j<=255; j++){
                if(dp[i][j]!=INF){
                    for(int k=0; k<M; k++){
                        ll num=j+C[k];
                        if(num<=0) num=0;
                        if(num>=255) num=255;
                        dp[i+1][num]=min(dp[i+1][num],dp[i][j]+(x[i]-num)*(x[i]-num));
                    }
                }
            }
        }

        ll ans=INF;
        for(int i=0; i<256; i++){
            ans=min(ans,dp[N][i]);
        }
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 530
memory_kb: 84776
final_rank: 20

code_snippet: #include <bits/stdc++.h>

using namespace std;

int main() {
  vector<int> res_list;
  while (true) {
    int N, M; cin >> N >> M;
    if (N == 0 && M == 0) break;
    vector<int> C(M + 1);
    for (int i = 1; i <= M; ++i) cin >> C[i];
    vector<int> X(N + 1);
    for (int i= 1; i <= N; ++i) cin >> X[i];

    vector<int> dp(256, INT_MAX);
    dp[128] = 0;
    for (int i = 1; i <= N; ++i) {
      vector<int> nextDp(256, INT_MAX);
      for (int y_prev = 0; y_prev < 256; ++y_prev) {
        if (dp[y_prev] == INT_MAX) continue;
        for (int j = 1; j <= M; ++j) {
          int c = C[j];
          int y = y_prev + c;
          y = min(y, 255);
          y = max(y, 0);
          int diff = X[i] - y;
          nextDp[y] = min(nextDp[y], dp[y_prev] + diff * diff);
        }
      }
      dp = nextDp;
    }
    auto res = min_element(dp.begin(), dp.end());
    res_list.push_back(*res);
  }
  for (int res: res_list) cout << res << endl;
  return 0;
}
accuracy: 1
time_ms: 340
memory_kb: 3272
final_rank: 1

code_snippet: #include <bits/stdc++.h>

using namespace std;

int main() {
  vector<int> res_list;
  while (true) {
    int N, M; cin >> N >> M;
    if (N == 0 && M == 0) break;
    vector<int> C(M + 1);
    for (int i = 1; i <= M; ++i) cin >> C[i];
    vector<int> X(N + 1);
    for (int i= 1; i <= N; ++i) cin >> X[i];

    vector<int> dp(256, INT_MAX);
    dp[128] = 0;
    for (int i = 1; i <= N; ++i) {
      vector<int> nextDp(256, INT_MAX);
      for (int y_prev = 0; y_prev < 256; ++y_prev) {
        if (dp[y_prev] == INT_MAX) continue;
        for (int j = 1; j <= M; ++j) {
          int c = C[j];
          int y = y_prev + c;
          y = min(y, 255);
          y = max(y, 0);
          nextDp[y] = min(nextDp[y], dp[y_prev] + (int)pow(X[i] - y, 2));
        }
      }
      dp = nextDp;
    }
    auto res = min_element(dp.begin(), dp.end());
    res_list.push_back(*res);
  }
  for (int res: res_list) cout << res << endl;
  return 0;
}
accuracy: 1
time_ms: 470
memory_kb: 3404
final_rank: 5

code_snippet: /*
AOJ Problem C: Differential Pulse Code Modulation
問題文の説明がわかりにく過ぎる
<問題の意味>
条件:
 コードブック = M個の整数の集合
  y0 = 128(固定値)
  yn = y_n-1 + (コードブックから選んだ任意の1つの値)
  xn = 入力信号(与えられる)
  -> Σ(xi-yi)^2が最小になるようにコードブックを選ぶ
例:
コードブック = {4, 2, 1, 0, -1, -2, -4} 
入力: x1=131,x2=137のとき
出力: y0=128(固定)
      y1 = y0 + (コードブックから選んだ任意の1つの値)
         = 128 + 4
         = 132
      y2 = y1 + 4
         = 132 + 4
         = 136
とすると、二乗和 = (x1-y1)^2 + (x2-y2)^2は最小になる

別には、例えば以下のようなコードブックの選び方ができる
  y1=128+(-4)=124, y2=124+2=126
  -> 二乗和 = (x1-y1)^2 + (x2-y2)^2が上記の二乗和より大きくなるのでNG
  
===================================================-
方針1: DP(コードブック) -> WA
コードブックの選び方をDPで全探索すればいけそう
-----------
WAの理由:
ある出力値からの遷移で、 出力値y:127,平方和:113 出力値y:128,平方和:113 の2つのパターンがあったときに先に出てきた、「出力値y:127,平方和:113」だけ残して、「出力値y:128,平方和:113」を捨ててしまうことがある → 最適な遷移が「出力値y:128,平方和:113」のときに間違いになってしまう
(例)
N=3
コードブック C={1,2,0,−2}
入力信号X=(137,120,134)
-----------

dp[i][j] = y0,...,yi-1を選んで、yi = yi-1 + コードブックのj番目の値としての二乗和が最小になるとき、[yiの値、二乗和]
遷移: dp[i][j] -> dp[i+1][k]  
 i:コードブックjを選んだときの最小二乗和になる選び方 -> i+1:コードブックkを選んだときの最小二乗和になる選び方

dpテーブル
  C[0] C[1] ... C[M-1]     (C[i]:コードブックのi番目の値)
--------------------------
y0
y1
...
yn
計算量: N*(M*M) <= 20000*16*16 = 8.2×10^7程度
===================================================-
方針2: DP(出力値) -> AC

dp[i][y] = 出力値をi-1個(y0,...,yi-1)を選んで、i番目の出力値としてyを選んだときの平方和の最小値
遷移: dp[i][y] -> M通り(コードブックの個数)
dpテーブル
    0 1 2 ... 256
--------------------------
y0
y1
...
yn

計算量: N*(256*M) <= 20000*256*M = 程度

PythonでTLEなのでC++に変換
*/

#include <bits/stdc++.h>
using namespace std;

const int MAX_Y = 255;
const int INIT_Y = 128;
const double INF = 1e18;

void calc_minsum(int N, int M) {
    vector<int> codebook(M);
    for (int i = 0; i < M; i++) cin >> codebook[i];
    vector<int> input_signals(N);
    for (int i = 0; i < N; i++) cin >> input_signals[i];

    vector<vector<double>> dp(N+1, vector<double>(MAX_Y+1, INF));
    dp[0][INIT_Y] = 0;

    for (int i = 0; i < N; i++) {
        int x = input_signals[i];
        for (int y = 0; y <= MAX_Y; y++) {
            if (dp[i][y] == INF) continue;
            for (int c : codebook) {
                int next_y = y + c;
                if (next_y < 0) next_y = 0;
                else if (next_y > MAX_Y) next_y = MAX_Y;
                double next_sum = dp[i][y] + (x - next_y) * (x - next_y);
                dp[i+1][next_y] = min(dp[i+1][next_y], next_sum);
            }
        }
    }

    double ans = INF;
    for (int y = 0; y <= MAX_Y; y++) {
        ans = min(ans, dp[N][y]);
    }
    cout << (long long)ans << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while (true) {
        int N, M;
        cin >> N >> M;
        if (N == 0 && M == 0) break;
        calc_minsum(N, M);
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 44288
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;

int main() {
    int N, M;
    while(cin >> N >> M, N) {
        vector<int> C(M);
        for(int i = 0; i < M; ++i) {
            cin >> C[i];
        }
        vector<int> x(N);
        for(int i = 0; i < N; ++i) {
            cin >> x[i];
        }
        vector<vector<int>> dp(N+1, vector<int>(256, 1e9));
        dp[0][128] = 0;
        for(int i = 0; i < N; ++i) {
            for(int j = 0; j < 256; ++j) {
                for(int k = 0; k < M; ++k) {
                    int next = min(255, max(0, j + C[k]));
                    dp[i+1][next] = min(dp[i+1][next], dp[i][j] + (next - x[i]) * (next - x[i]));
                }
            }
        }
        cout << *min_element(dp[N].begin(), dp[N].end()) << endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 23908
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;

const int inf = (1<<30);
int dp[20009][256];

int main() {
    //cout << 1 << endl;
    while(true){
        int N, M;
        cin >> N >> M;
        if(N == 0 && M == 0){
            break;
        }

        vector<int> cb(M), in(N);
        for(int i = 0; i < M; i++){
            cin >> cb[i];
        }
        for(int i = 0; i < N; i++){
            cin >> in[i];
        }
        //cout << 1 << endl;

        for(int i = 0; i < N+1; i++){
            for(int j = 0; j < 256; j++){
                dp[i][j] = inf;
            }
        }
        dp[0][128] = 0;
        for(int i = 0; i < N; i++){
            for(int j = 0; j < 256; j++){
                if(dp[i][j] == inf) continue;

                for(int k = 0; k < M; k++){
                    int num = j + cb[k];
                    if(num < 0) num = 0;
                    if(num > 255) num = 255;
                    int gosa = abs(in[i] - num);
                    dp[i+1][num] = min(dp[i+1][num], dp[i][j] + gosa * gosa);
                }
            }
        }

        int ans = inf;
        for(int i = 0; i < 256; i++){
            ans = min(dp[N][i], ans);
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 23520
final_rank: 3

code_snippet: #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;

const int START = 128;
const int LIMIT = 255;
const int INF = (1LL<<31) - 1;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while (true) {
        int N, M;
        cin >> N >> M;
        if (!N && !M) break;

        vector<int> code(M);
        for (int i = 0; i < M; ++i) cin >> code[i];

        vector<int> signal(N);
        for (int i = 0; i < N; ++i) cin >> signal[i];

        vector<vector<int>> memo(N+1, vector<int>(LIMIT+1, INF));
        
        for (int i = 0; i <= N; ++i) {
            int sig_idx = i-1;
            if (i == 0) {
                memo[0][START] = 0;
            }
            else {
                for (int j = 0; j <= LIMIT; ++j) {
                    for (int k = 0; k < M; ++k) {
                        if (memo[i-1][j] != INF) {
                            int nxt = j + code[k];
                            if (nxt <= 0) nxt = 0;
                            if (LIMIT <= nxt) nxt = LIMIT;
                            int add = (signal[sig_idx]-nxt)*(signal[sig_idx]-nxt);
                            memo[i][nxt] = min(memo[i][nxt], memo[i-1][j] + add);
                        }
                    }
                }
            }
        }
        int result = INF;
        for (int i = 0; i <= LIMIT; ++i) {
            result = min(result, memo[N][i]);
        }
        cout << result << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 510
memory_kb: 23992
final_rank: 11

code_snippet: #include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <tuple>
#include <set>
#include <map>
#include <bitset>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cassert>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
using namespace std;
typedef long long ll;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define all(v) v.begin(), v.end()

ll llpow(ll a, ll t)
{
  ll res = 1;
  rep(i, t) res *= a;
  return res;
}

ll inf = std::numeric_limits<ll>::max();

int main()
{
  vector<vector<ll>> css;
  vector<vector<ll>> xss;
  while (true)
  {
    ll n, m;
    cin >> n >> m;
    if (!n && !m)
    {
      break;
    }
    vector<ll> cs(m);
    rep(i, m)
    {
      cin >> cs[i];
    }
    vector<ll> xs(n);
    rep(i, n)
    {
      cin >> xs[i];
    }
    css.push_back(cs);
    xss.push_back(xs);
  }
  vector<ll> ans;
  rep(i, css.size())
  {
    vector<ll> cs = css[i];
    vector<ll> xs = xss[i];
    ll n = xs.size();
    ll m = cs.size();
    vector<vector<ll>> dp(n, vector<ll>(256, inf));
    rep(i, n)
    {
      rep(j, 256)
      {
        rep(k, m)
        {
          if (!i)
          {
            if (128 + cs[k] == j)
            {
              dp[i][j] = min(dp[i][j], llpow(xs[i] - j, 2));
              continue;
            }
            if (j == 0 && 128 + cs[k] < 0)
            {
              dp[i][j] = min(dp[i][j], llpow(xs[i] - j, 2));
              continue;
            }
            if (j == 255 && 128 + cs[k] > 255)
            {
              dp[i][j] = min(dp[i][j], llpow(xs[i] - j, 2));
              continue;
            }
            continue;
          }
          if (j + cs[k] >= 0 && j + cs[k] <= 255 && dp[i - 1][j] != inf)
          {
            dp[i][j + cs[k]] = min(dp[i][j + cs[k]], dp[i - 1][j] + llpow(xs[i] - (j + cs[k]), 2));
            continue;
          }
          if (j + cs[k] < 0 && dp[i - 1][j] != inf)
          {
            dp[i][0] = min(dp[i][0], dp[i - 1][j] + llpow(xs[i], 2));
            continue;
          }
          if (j + cs[k] > 255 && dp[i - 1][j] != inf)
          {
            dp[i][255] = min(dp[i][255], dp[i - 1][j] + llpow(xs[i] - 255, 2));
            continue;
          }
        }
      }
    }
    ll mn = inf;
    rep(i, 256)
    {
      mn = min(mn, dp[n - 1][i]);
    }
    ans.push_back(mn);
  }
  rep(i, ans.size())
  {
    cout << ans[i] << endl;
  }
}
accuracy: 1
time_ms: 540
memory_kb: 44832
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
const ll INF = LLONG_MAX / 4;
const ll mod1 = 1000000007;
const ll mod9 = 998244353;
const ll Hash = 10000000000000061;
#define all(a) (a).begin(),(a).end()
#define rep(i, n) for (ll i = 0; (i) < (n); ++(i))
ll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
ll dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};
template <typename T>
bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; }
    return false;
}
template <typename T>
bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; }
    return false;
}

#define EPS (1e-10)
#define equals(a, b) (fabs((a) - (b)) < EPS)
class Point {
public:
    ld x;
    ld y;
    Point(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}
    Point operator+(Point p) { return Point(x + p.x, y + p.y); }
    Point operator-(Point p) { return Point(x - p.x, y - p.y); }
    Point operator*(ld a) { return Point(a * x, a * y); }
    Point operator/(ld a) { return Point(x / a, y / a); }

    ld abs() { return sqrt(norm()); }
ld norm() { return x * x + y * y; }

    bool operator<(const Point& p) const {
        return !equals(x, p.x) ? x < p.x : y < p.y;
    }
    bool operator==(const Point& p) const {
        return fabs(x - p.x) < (1e-10) && fabs(y - p.y) < (1e-10);
    }
};
typedef Point Vector;
struct Segment {
    Point A;
    Point B;
};
typedef Segment Line;
class Circle {
public:
    Point C;
    ld r;
    Circle(Point C = Point(), ld r = 0.0) : C(C), r(r) {}
};
typedef vector<Point> Polygon;

int solve(){
    ll N, M; cin >> N >> M;
    if(N == 0) return 0;
    vector<ll> c(M); rep(i, M) cin >> c[i];
    sort(all(c));
    vector<ll> a(N); rep(i, N) cin >> a[i];
    ll W = 256;
    vector<vector<ll>> dp(N+1, vector<ll>(W, 4e18)); dp[0][128]= 0;
    rep(i, N){
        rep(k, W){
            if(dp[i][k] == 4e18) continue;
            rep(l, M){
                ll x = k + c[l];
                if(x < 0) x = 0;
                if(x > W-1) x = W-1;
                chmin(dp[i+1][x], dp[i][k] + (a[i] - x) * (a[i] - x));
            }
        }
    }
    ll ans = 4e18;
    rep(i, W) chmin(ans, dp[N][i]);
    cout << ans << endl;
    return 1;
}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    int t = 1;
    // cin >> t;
    while(t){
        t = solve();
    }
}
accuracy: 1
time_ms: 520
memory_kb: 43948
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using a2 = array<ll, 2>;
using a3 = array<ll, 3>;

template <typename A> void chmin(A &l, const A &r) {
    if(r < l)
        l = r;
}
template <typename A> void chmax(A &l, const A &r) {
    if(l < r)
        l = r;
}

ll mod = 998244353;

void init() {}

ll n, m;
vector<ll> v, w;
void input() {
    cin >> n >> m;
    v.resize(m);
    w.resize(n);
    for(auto &x : v)
        cin >> x;
    for(auto &x : w)
        cin >> x;
}
void solve() {
    vector<vector<ll>> dp(n + 1, vector<ll>(256, 1e18));
    dp[0][128] = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            for(int k = 0; k < 256; k++) {
                ll idx = max(0LL, min(255LL, k + v[j]));
                chmin(dp[i + 1][idx], dp[i][k] + (idx - w[i]) * (idx - w[i]));
            }
        }
    }
    cout << *min_element(dp.back().begin(), dp.back().end()) << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    init();
    while(1) {
        input();
        if(n == 0)
            break;
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 510
memory_kb: 44212
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rrep(i,start,end) for (ll i = start;i >= (ll)(end);i--)
#define repn(i,end) for(ll i = 0; i <= (ll)(end); i++)
#define reps(i,start,end) for(ll i = start; i < (ll)(end); i++)
#define repsn(i,start,end) for(ll i = start; i <= (ll)(end); i++)
#define each(p,a) for(auto &p:a)
typedef vector<ll> vll;
typedef vector<pair<ll ,ll>> vpll;
typedef vector<vector<ll>> vvll;
typedef set<ll> sll;
typedef map<ll , ll> mpll;
typedef pair<ll ,ll> pll;
typedef tuple<ll , ll , ll> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (ll)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 60;
const ld EPS = 1e-9;
 
ll lceil(ll a,ll b){if(a%b==0){return a/b;}if(a>=0){return (a/b)+1;}else{return -((-a)/b);}}
ll lfloor(ll a,ll b){if(a%b==0){return a/b;}if(a>=0){return (a/b);}else{return -((-a)/b)-1;}}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
//0indexed
inline ll topbit(ll a){assert(a != 0);return 63 - __builtin_clzll(a);}
inline ll smlbit(ll a){assert(a != 0);return __builtin_ctzll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
  
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;

void solve(int n, int m){
  vector<ll> c(m);
  for (int i=0; i<m; ++i) cin >> c[i];
  vector<ll> x(n);
  for (int i=0; i<n; ++i) cin >> x[i];

  // int inf = 1 << 30;
  ll mx = 255;
  vector<vector<ll>> dp(n+1, vector<ll>(mx+1, INF));

  dp[0][128] = 0;
  for (ll i=0; i<n; ++i) {
    for (ll j=0; j<=mx; ++j)if(dp[i][j] < INF){
      for (ll k=0; k<m; ++k) {
        if (c[k] >= 0) {
          dp[i+1][min(mx, j+c[k])] = min(
            dp[i+1][min(mx, j+c[k])],dp[i][j] + (min(mx, j+c[k]) - x[i])*(min(mx, j+c[k]) - x[i])
          );
        } else {
          dp[i+1][max(0LL, j+c[k])] = min(
            dp[i+1][max(0LL, j+c[k])],dp[i][j] + (max(0LL, j+c[k]) - x[i])*(max(0LL, j+c[k]) - x[i])
          );
        }
      }
    }

    // cout << "=====" << endl;
    // for (auto xx: dp) {
    //   for (auto x: xx) {
    //     cout << x << ' ';
    //   }
    //   cout << endl;
    // }
  }
  ll ans = INF;
  for (int i=0; i<=mx; ++i) {
    ans = min(ans, dp[n][i]);
  }
  cout << ans << endl;
}

int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);
  while (true) {
    int n, m;
    cin >> n >> m;
    if (n == 0 && m == 0) break;
    solve(n, m);
  }
}
accuracy: 1
time_ms: 370
memory_kb: 44288
final_rank: 8

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define int long long

int solve(){
    int n,m;
    cin>>n>>m;
    if(n==0 && m==0){
        return 0;
    }
    vector<int> mlist(m,0);
    for(int i=0;i<m;i++){
        cin>>mlist.at(i);
    }
    vector<int> xlist(n,0);
    for(int i=0;i<n;i++){
        cin>>xlist.at(i);
    }
    vector<vector<int>> dp(n+1,vector<int>(256,8e18));
    dp.at(0).at(128)=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<256;j++){
            for(int k=0;k<m;k++){
                dp.at(i+1).at(max(0LL,min(255LL,j+mlist.at(k))))=min(dp.at(i).at(j)+(xlist.at(i)-(max(0LL,min(255LL,j+mlist.at(k)))))*(xlist.at(i)-(max(0LL,min(255LL,j+mlist.at(k))))),dp.at(i+1).at(max(0LL,min(255LL,j+mlist.at(k)))));
            }
        }
    }
    int ans=8e18;
    for(int j=0;j<256;j++){
        ans=min(ans,dp.at(n).at(j));
    }
    cout<<ans<<endl;
    return 1;
}

#undef int
int main(){
	#define int long long
	while(solve()){}
}
accuracy: 1
time_ms: 570
memory_kb: 44288
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ll long long    
#define INF 1e18
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    vector<ll> ans;
    while(1){
        ll n,m;cin>>n>>m;
        if(n==0&&m==0)break;
        vector<ll> a(m),b(n);
        for(auto& i:a)cin>>i;
        for(auto& i:b)cin>>i;
        vector<vector<ll>> dp(n+1,vector<ll>(259,INF));
        for(ll i=0;i<m;i++){
            if(128+a[i]<0)dp[0][0]=0;
            else if(128+a[i]>255)dp[0][255]=0;
            else dp[0][128+a[i]]=0;
        }
        for(ll i=0;i<n;i++){
            for(ll j=0;j<=255;j++){
                for(ll k=0;k<m;k++){
                    if(j+a[k]<0)dp[i+1][0]=min(dp[i+1][0],dp[i][j]+(ll)pow(b[i]-j,2));
                    else if(j+a[k]>255)dp[i+1][255]=min(dp[i+1][255],dp[i][j]+(ll)pow(b[i]-j,2));
                    else dp[i+1][j+a[k]]=min(dp[i+1][j+a[k]],dp[i][j]+(ll)pow(b[i]-j,2));
                }
            }
    }ans.push_back(*min_element(dp[n].begin(),dp[n].end()));
    }
    for(auto& i:ans)cout<<i<<endl;
}
accuracy: 1
time_ms: 420
memory_kb: 44292
final_rank: 10

code_snippet: #include <bits/stdc++.h>

#define paiza

#ifndef paiza
#include <boost/multiprecision/cpp_int.hpp>
#include <atcoder/all>
#endif

#ifndef paiza
#ifndef ONLINE_JUDGE
#define GLIBCXX_DEBUG
#define dev
#endif
#endif
#define rep(i,n) for(ll i=0; i<(n); i++)
#define rrep(i,n) for(ll i=1; i<=(n); i++)
#define drep(i,n) for(ll i=(n)-1; i>=0; i--)
#define xfor(i,s,e) for(ll i=(s); i<(e); i++)
#define dfor(i,s,e) for(ll i=(s)-1; i>=(e); i--)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define chmax(x,y) x = max(x,y)
#define chmin(x,y) x = min(x,y)
#define popcnt(s) ll(popcount<ull>(uint64_t(s)))
using namespace std;using ll=long long;using ull=unsigned long long;using dl=long double;
template<typename T>istream&operator>>(istream&is,pair<T,T>&v){is>>v.first>>v.second;return is;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(auto&in:v)is>>in;return is;}
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(auto&in:v)os<<in<<' ';return os;}
ll modpow(ll a, ll b, ll mod) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a) % mod;a = (a * a) % mod;b >>= 1;}return res;}
ll POW(ll a, ll b) {ll res = 1;while (b > 0) {if (b & 1) res = (res * a);a = (a * a);b >>= 1;}return res;}
/*MOD MUST BE A PRIME NUMBER!!*/ll moddiv(const ll a, const ll b, const ll mod) {ll modinv = modpow(b, mod-2, mod);return (a * modinv) % mod;}
constexpr ll INF = 2e10;
ll nC2(const ll i){return i>2?i*(i-1)/2:0;}ll nC3(const ll i){return i>3?i*(i-1)*(i-2)/6:0;}ll nC4(const ll i){return i>4?i*(i-1)*(i-2)*(i-3)/24:0;}ll nC5(const ll i){return i>5?i*(i-1)*(i-2)*(i-3)*(i-4)/120:0;}ll nC6(const ll i){return i>6?i*(i-1)*(i-2)*(i-3)*(i-4)*(i-5)/720:0;}
void warshall_floyd(vector<vector<ll>>& dist) {const ull n = dist.size();rep(k, n) rep(i, n) rep(j, n) {dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);}}
#define YES {cout<<"Yes\n";return 0;}
#define NO {cout<<"No\n";return 0;}
#define yn YES else NO

#ifndef paiza
//using lll = boost::multiprecision::cpp_int;
using lll = boost::multiprecision::int128_t;
using namespace atcoder;
//using mint = modint1000000007;
//using mint = modint998244353;
using mint = modint; // custom mod
//atcoder::modint::set_mod(m);
// DSU == UnionFind
#endif

#define vc vector
using P = pair<ll, ll>;using vl = vc<ll>;using vb=vc<bool>;
ll _min(const vl& v) {ll smallest = INF;for(auto i : v) chmin(smallest, i);return smallest;}
ll _max(const vl& v) {ll biggest = -INF;for(auto i : v) chmax(biggest, i);return biggest;}
template<typename T>void cs(vector<T>&v){xfor(i,1,v.size())v[i]+=v[i-1];}
bool operator<(pair<ll,ll> p1, pair<ll,ll> p2) {return p1.first == p2.first ? p1.second < p2.second : p1.first < p2.first;}

#define endl "\n"

vl dx = {-1, 1, 0, 0, -1, 1, -1, 1};
vl dy = {0, 0, 1, -1, -1, -1, 1, 1};

constexpr ll mod = 998244353;

int main() {
    ios_base::sync_with_stdio(false);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cout << fixed << setprecision(50);

    while (true) {
        ll N,M;
        cin>>N>>M;
        if (N==0&&M==0)break;

        vl C(M), x(N);
        cin>>C>>x;

        auto round = [](ll i){return
            256<=i ? 255
            : 0>i ? 0
            : i
            ;
        };
        auto cost = [](ll target, ll actual){return (target-actual)*(target-actual);};

        // dp[i][j] ... i個目の値を符号化した後にjにするときの最小の累積コスト
        vc<vl> dp(N,  vc(256,INF));

        for (auto C_i: C) dp[0][round(128+C_i)] = cost(x[0], round(128+C_i));
        rep(i,N-1) { // 配るDP
            rep(j, 256) {
                for (const auto C_i : C) {
                    chmin(dp[i+1][round(j+C_i)], dp[i][j]+cost(x[i+1], round(j+C_i)));
                }
            }
        }

        cout << *min_element(all(dp[N-1])) << endl;
    }
}
accuracy: 1
time_ms: 350
memory_kb: 44288
final_rank: 7