// Arup Guha
// 1/4/2014
// Solution to 2014 Mercer Contest Problem 13: Tree Sales - runs in O(nd) time
// where n = # nodes, d = maximum depth.

import java.util.*;

public class prob13 {

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);
		int numCases = stdin.nextInt();

		// Go through each case.
		for (int loop=1; loop<=numCases; loop++) {

			// Print case header.
			System.out.println("COMPANY "+loop);

			// Set up tree first.
			int n = stdin.nextInt();
			String cmd = stdin.next();
			String dummy = stdin.next();
			String root = stdin.next();
			node tree = new node(root, null);

			// Use a hashmap so we can find nodes in the tree quickly.
			HashMap<String,node> map = new HashMap<String,node>();
			map.put(root, tree);

			// Process the rest of the commands.
			for (int i=1; i<n; i++) {

				cmd = stdin.next();

				// Perform an add. Attach the new employee to the right place.
				if (cmd.equals("ADD")) {
					String sponsor = stdin.next();
					String newbie = stdin.next();
					node parent = map.get(sponsor);
					node newNode = new node(newbie, parent);
					parent.addChild(newNode);
					map.put(newbie, newNode);
				}

				// Find the node making a sale and process it.
				else if (cmd.equals("SALE")) {
					String name = stdin.next();
					int amt = stdin.nextInt();
					map.get(name).sale(amt);
				}

				// Find the node and print the total sales in this subtree.
				else if (cmd.equals("QUERY")) {
					String name = stdin.next();
					System.out.println(map.get(name).totalSales);
				}

			}
		}
	}
}

class node {

	public String name;
	public int totalSales;
	public node parent;
	public LinkedList<node> kids;

	// Sets up a new node.
	public node(String n, node myParent) {
		name = n;
		totalSales = 0;
		parent = myParent;
		kids = new LinkedList<node>();
	}

	// Add a child to this node.
	public void addChild(node n) {
		kids.add(n);
	}

	// Perform a sale on this node, updating all ancestral nodes accordingly.
	public void sale(int value) {
		totalSales += value;
		if (parent != null)
			parent.sale(value);
	}
}