#include <bits/stdc++.h>
using namespace std;
struct Node;
struct Seeker;
const int first_signal_log = 128;
int n;
int m;
vector<short> book;
vector<short> seq;
priority_queue<Seeker> que;
set<Node> close_list;
template <class T>
void print(const vector<T>& vec) {
  for (auto v : vec) {
    cout << " " << v;
  }
  cout << endl;
}
struct Node {
  string k = "";
  void push_back(int key) {
    assert(0 <= key);
    assert(key <= 16);
    k.push_back((char)key + 65);
  }
  void print() const {
    cout << "(";
    for (auto c : k) {
      cout << (int)c - 65 << " ";
    }
    cout << k;
    cout << ") ";
  }
};
bool operator<(const Node& a, const Node& b) { return a.k < b.k; }
bool operator==(const Node& a, const Node& b) { return a.k == b.k; }
struct Seeker {
  Node node;
  uint cost = 0;
  int y = first_signal_log;
  Seeker(Node _node) : node(_node) {}
  void print() const {
    node.print();
    cout << y << " " << cost << endl;
  }
  void change(int code) {
    y += code;
    y = max(0, y);
    y = min(y, 255);
  }
};
bool operator<(const Seeker& a, const Seeker& b) { return a.cost > b.cost; }
void seek(Seeker s, size_t key) {
  s.node.push_back(key);
  if (close_list.count(s.node) > 0) {
    return;
  }
  close_list.insert(s.node);
  size_t time = s.node.k.size();
  auto code = book[key];
  s.change(code);
  auto diff = s.y - seq[time];
  s.cost += diff * diff;
  que.push(s);
}
bool isGoal(const Seeker& s) {
  int time = s.node.k.size();
  return n == time;
}
uint solve() {
  Node start_node;
  Seeker start(start_node);
  que.push(start);
  while (que.empty() == false) {
    Seeker s = que.top();
    if (isGoal(s)) {
      return s.cost;
    }
    que.pop();
    for (size_t key = 0; key < book.size(); key++) {
      seek(s, key);
    }
  }
  return -1;
}
void clearQue() {
  while (que.empty() == false) {
    que.pop();
  }
}
void input() {
  clearQue();
  close_list.clear();
  book.resize(m);
  for (auto& val : book) {
    cin >> val;
  }
  seq.resize(n + 1);
  seq[0] = first_signal_log;
  for (int i = 1; i < n + 1; i++) {
    cin >> seq[i];
  }
}
int main() {
  while (true) {
    cin >> n >> m;
    if (n == 0 and m == 0) {
      break;
    }
    input();
    cout << solve() << endl;
  }
  return 0;
}
