1. 
import java.util.Arrays;
import java.util.Scanner;

/**
* Angewandte Mathematik, SS11
* Problem: 538 Balance Bank Account
* Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=14&page=show_problem&problem=1170
*
* @author Benedikt Zšnnchen
* @author Erik Wenzel
* @version 1.0, 17/04/2011
*
* Method : Greedy, ArraySort
* Status : Accepted
* Runtime: 1.640
*
*/

public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String line;
int c = 0;
while(true)
{
c++;
String[] tmp = reader.nextLine().split(" ");
int nameCount = Integer.parseInt(tmp[0]);
int caseCount = Integer.parseInt(tmp[1]);

BankAccount[] bankAccounts = new BankAccount[nameCount];

if(nameCount == 0 && caseCount == 0)
{
break;
}
System.out.println("Case #"+c);

// Einlesen
for(int i=0; i<nameCount; i++)
{
bankAccounts[i] = new BankAccount(reader.nextLine());
}

for(int i=0; i<caseCount; i++)
{
line = reader.nextLine();
tmp = line.split(" ");
int money = Integer.parseInt(tmp[2]);
getBankAccount(bankAccounts, tmp[0]).value -= money;
getBankAccount(bankAccounts, tmp[1]).value += money;
}

// Sortieren
Arrays.sort(bankAccounts);

// Berechnen
int highestIndex = 0;
int lowestIndex = bankAccounts.length-1;
while(lowestIndex>highestIndex)
{
int lowest = Math.abs(bankAccounts[lowestIndex].value);
int highest = bankAccounts[highestIndex].value;

if(lowest > highest)
{
bankAccounts[lowestIndex].value += highest;
bankAccounts[highestIndex].value = 0;
System.out.println(bankAccounts[highestIndex].name+" "+bankAccounts[lowestIndex].name+" "+highest);
highestIndex++;
}
else if(highest > lowest)
{
bankAccounts[highestIndex].value -= lowest;
bankAccounts[lowestIndex].value = 0;
System.out.println(bankAccounts[highestIndex].name+" "+bankAccounts[lowestIndex].name+" "+lowest);
lowestIndex--;
}
else
{
bankAccounts[highestIndex].value = 0;
bankAccounts[lowestIndex].value = 0;
if(!(lowest==0 && highest ==0))
{
System.out.println(bankAccounts[highestIndex].name+" "+bankAccounts[lowestIndex].name+" "+highest);
}
highestIndex++;
lowestIndex--;
}
}

System.out.println();
}
}

/**
* sucht nach einem BankAccount in einem Array anhand des namens
* @param bankAccounts array
* @param name
* @return BankAccount
*/
public static BankAccount getBankAccount(BankAccount[] bankAccounts, String name)
{
for(int i=0; i<bankAccounts.length; i++)
{
if(bankAccounts[i].name.equals(name))
{
return bankAccounts[i];
}
}
return null;
}
}

/**
* Hilfsklasse um den String zum Wert zuweisen zu kšnnen
* und um besser sortieren zu kšnnen (Comparable)
* @author Benedikt Zšnnchen
* @author Erik Wenzel
*/
class BankAccount implements Comparable<BankAccount>
{
int value;
String name;

BankAccount(String name)
{
this.name = name;
}

@Override
public int compareTo(BankAccount o)
{
return o.value - value;
}
}