#include<iostream>
using namespace std;
struct group {
int x;
int y;
int num;
int dir;
};
int dir[5][2] = { {0,0},{-1,0},{1,0},{0,-1},{0,1} };
group arr[1000] = {};
int dir_change(int now_dir) {
if (now_dir == 1 || now_dir == 3) {
return now_dir + 1;
}
else if (now_dir == 2 || now_dir == 4) {
return now_dir - 1;
}
}
int main() {
int T;
cin >> T;
for (int t = 1; t <= T; t++) {
int N, M, K;
cin >> N >> M >> K;
for (int i = 0; i < K; i++) {
cin >> arr[i].x >> arr[i].y >> arr[i].num >> arr[i].dir;
}
while (M > 0) {
for (int i = 0; i < K; i++) {
if(arr[i].num == 0)
continue;
arr[i].x = arr[i].x + dir[arr[i].dir][0];
arr[i].y = arr[i].y + dir[arr[i].dir][1];
}
for (int i = 0; i < K; i++) {
if (arr[i].num == 0)
continue;
int total = arr[i].num;
int index = i;
for (int j = i + 1; j < K; j++) {
if (arr[j].num == 0)
continue;
if (arr[index].x == arr[j].x && arr[index].y == arr[j].y) {
total += arr[j].num;
if (arr[index].num < arr[j].num) {
arr[index].num= 0;
index = j;
}
else {
arr[j].num = 0;
}
}
}
arr[index].num = total;
if (arr[index].x == 0 || arr[index].y == 0 || arr[index].x == N - 1 || arr[index].y == N - 1) {
arr[index].num /= 2;
arr[index].dir = dir_change(arr[index].dir);
}
}
M--;
}
int group_total = 0;
for (int i = 0; i < K; i++) {
group_total += arr[i].num;
}
cout << "#" << t << " " << group_total << endl;
}
return 0;
}