import java.util.*;

public class E_Andy {

	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		
		while(true)
		{
			String line = s.nextLine();
			
			if(line.contains("ENDOFINPUT")) break;
			
			LinkedList<Reaction> reacts = new LinkedList<Reaction>();
			
			while(!line.contains("0 0 0")) 
			{
				Scanner lScanner = new Scanner(line);
				String c1 = lScanner.next();
				String c2 = lScanner.next();
				int heat = lScanner.nextInt();
				
				reacts.add(new Reaction(c1, c2, heat));
				
				line = s.nextLine();
			}
			
			TreeMap<String, Integer> chems = new TreeMap<String, Integer>();
			
			while(!(line = s.nextLine()).contains("0 0"))
			{
				Scanner lScanner = new Scanner(line);
				String c = lScanner.next();
				int amt = lScanner.nextInt();
				
				chems.put(c, amt);
			}
			
			ArrayList<Reaction> toRemove = new ArrayList<Reaction>(reacts.size());
			for(Reaction r : reacts)
				if(chems.get(r.c1) == null || chems.get(r.c2) == null) toRemove.add(r);

			for(Reaction r : toRemove)
				reacts.remove(r);
			
			HashMap<TreeMap<String, Integer>, Integer> cache = new HashMap<TreeMap<String,Integer>, Integer>();
			cache.put(chems, 0);
			
			Stack<TreeMap<String, Integer>> stack = new Stack<TreeMap<String,Integer>>();
			stack.add(chems);
			
			while(!stack.isEmpty())
			{
				TreeMap<String, Integer> curr = stack.pop();
				int currHeat = cache.get(curr);
				
				for(Reaction r : reacts)
				{
					int a1 = curr.get(r.c1);
					int a2 = curr.get(r.c2);
					int amt = Math.min(a1, a2);
										
					if(amt == 0) continue;
					
					int nextHeat = currHeat + amt * r.heat;
					
					TreeMap<String, Integer> next = (TreeMap<String, Integer>)curr.clone();
					next.put(r.c1, a1 - amt);
					next.put(r.c2, a2 - amt);
					
					Integer fromCache = cache.get(next);
					
					if(fromCache == null || fromCache < nextHeat)
					{
						cache.put(next, nextHeat);
						stack.add(next);
					}
				}
			}
			
			int max = 0;
			for(int change : cache.values())
				if(max < change)
					max = change;
			
			System.out.println("The temperature in the jar will change by at most " + max + " degrees.");
		}
	}
	
	private static class Reaction
	{
		public String c1, c2;
		public int heat;
		
		public Reaction(String c1, String c2, int heat)
		{
			this.c1 = c1;
			this.c2 = c2;
			this.heat = heat;
		}
	}
}
