#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 5;
const int M = 30;
struct portal3 {
int v, sens, ord;
};
int n, m, x1[N], x2[N], y1[N], y2[N], c[N], s[N], nr, tmin[M], tp[M], ss[N*N];
bool fr[N];
portal3 a[N];
bool comp(portal3 x, portal3 y) {
return x.ord < y.ord ? true : false;
}
inline int modul(int x, int y) {
if (x > y)
return x - y;
return y - x;
}
void add(int a[], int x) {
if (a[0] == 0)
a[1] = x;
else
a[1] += x;
int i = 1, t = 0;
while (a[i] > 9) {
t = a[i] / 10;
a[i] %= 10;
if (i + 1 > a[0])
a[i + 1] = 0;
a[++i] += t;
}
if (i > a[0])
a[0] = i;
}
void timp() {
sort(a+1, a+nr+1, comp);
int xc = 0, yc = 0;
tp[0] = 0;
for (int i = 1; i <= nr; ++i)
if (a[i].sens == 1) {
add(tp, modul(x1[a[i].v], xc) + modul(y1[a[i].v], yc));
add(tp, c[a[i].v]);
xc = x2[a[i].v];
yc = y2[a[i].v];
}
else {
add(tp, modul(x2[a[i].v], xc) + modul(y2[a[i].v], yc));
add(tp, c[a[i].v]);
xc = x1[a[i].v];
yc = y1[a[i].v];
}
add(tp, modul(n, xc) + modul(m, yc));
}
void copiaza(int a[],int b[]) {
for (int i = 0; i <= a[0]; ++i)
b[i] = a[i];
}
bool compar(int a[],int b[]) {
if (a[0] < b[0])
return true;
if (a[0] > b[0])
return false;
int i = a[0];
while (i >= 1 && a[i] == b[i])
--i;
if (a[i] < b[i] || i == -1)
return true;
return false;
}
void permutari(int p) {
if (p == nr + 1) {
timp();
if (tmin[0] == 0 || compar(tp, tmin))
copiaza(tp, tmin);
return;
}
for (int i = 1; i <= nr; ++i)
if (!fr[i]) {
fr[i] = true;
a[p].ord = i;
permutari(p + 1);
fr[i] = false;
}
}
void bkt(int p) {
if (p == 3) {
nr = 0;
for (int i = 1; i < 4; ++i)
if (s[i] != 0) {
a[++nr].v = i;
a[nr].sens = s[i];
}
permutari(1);
return;
}
for (int i = 0; i < 3; ++i) {
s[p + 1] = i;
bkt(p + 1);
}
}
void afis(int a[]) {
for (int i = a[0]; i > 0; --i)
printf("%d", a[i]);
}
void rez() {
int t;
scanf("%d", &t);
for (int k = 1; k <= t; ++k) {
scanf("%d%d", &n, &m);
for (int i = 1; i < 4; ++i)
scanf("%d%d%d%d%d", &x1[i], &y1[i], &x2[i], &y2[i], &c[i]);
bkt(0);
afis(tmin);
tmin[0] = 0;
}
}
int main() {
freopen("portal3.in", "r", stdin);
freopen("portal3.out", "w", stdout);
rez();
return 0;
}