#include <stdio.h>
#include <iostream>
#include <string>
#include "testlib.h"
using namespace std;

string names[20];

string ss, pa, ji;

int n, m, na;

char *fmt = "Case #%d";

char s[100000], s1[100000], s2[100000]; string ss1, ss2;

int delta[20];

int index(string s)
{
	for (int i = 0; i < n; i++)
		if (names[i] == s) return i;
	return -1;
}

void calc()
{
	memset(delta, 0, sizeof(delta));
	for (int i = 0; i < n; i++)
		names[i] = inf.readString();
	for (int i = 0; i < m; i++)
	{
		ss = inf.readString();
		int t, k1, k2;
		sscanf(ss.c_str(), "%s %s %d", s1, s2, &t); ss1 = s1; ss2 = s2;
		k1 = index(ss1); k2 = index(ss2);
		delta[k1] -= t; delta[k2] += t;
	}
}

int main(int argc, char *argv[])
{
	registerTestlibCmd(argc, argv);

	int nt = 0;

	while (1)
	{
		ji = inf.readString();
		sscanf(ji.c_str(), "%d %d", &n, &m);
		if (!n || !m) break;
		calc();
		//
		nt++;
		sprintf(s, fmt, nt);
		pa = ouf.readString();
		ss = s;
		if (ss != pa)
			quitf(_wa, "Wrong answer. Expected: '%s', founded: '%s'", s, pa.c_str());
		na = 0;
		while (1)
		{
			ss = ouf.readString();
			if (ss.length() == 0) break;
			na++;
			if (na == n)
				quitf(_wa, "Answer too long");
			int k1, k2, t;
			sscanf(ss.c_str(), "%s %s %d", s1, s2, &t); ss1 = s1; ss2 = s2;
			k1 = index(ss1); 
			if (k1 == -1)
				quitf(_wa, "Unknown name in output: '%s'", s1);
			k2 = index(ss2);
			if (k2 == -1)
				quitf(_wa, "Unknown name in output: '%s'", s2);
			delta[k1] -= t; delta[k2] += t;
		}
		for (int i = 0; i < n; i++)
			if (delta[i])
				quitf(_wa, "Not balanced");
	}
	quitf(_ok, "%d cases", nt);
	return 0;
}
