sharethefare-1

WizKid went on a trip to Wonderland with his classmates. Now, as you know, going on trips incurs costs including hotel costs, fooding, shopping, etc. And when many people go together, usually one person pays and it is expected that the others will pay back their share. But, after a few days people lost track of who owed whom how much and there was a lot of confusion. 
So WizKid set down to make a program which will help solve all these problems in future. He will record the details of all the people going on the trip and the details of each transaction made on the trip. 
Note: It is not necessary that all the people were present in all transactions. Only those present will share the amount. So he also has to note who all were present, who paid and the amount paid. 
Even after this, one more issue remained about what happens when the amount spent could not be divided equally integrally to each person. Well, he decided that the person who paid the bill will have to bear the little extra cost himself on each bill. 

Now, we need you to simulate the same and give the final summary for each person accordingly.

Input:
First line contains T which is the number of test cases.
First line of each test case consists of 2 integers N and Q where N is the number of people who went on the trip and Q is the number of transactions made. 
N lines follow, each containing the names of the N persons who went on the trip. Each name will be distinct and will be a single word consisting of lowercase or uppercase alphabets only.

Q transactions follow each containing the details of each transaction made.
The first line of each transaction contains the name of the person who paid for the transaction.
The second line of each transaction contains the amount paid by the person for the transaction.
The third line of each transaction contains the number of people(other than the person who paid) M between whom this amount is to be split.
M lines follow each containing the names of the people between whom this amount is to be split.
Output:
For each test case, print N lines containing the final dues for each person in the following manner : 

If a person X is supposed to get Y money from the others, then print "X is owed Y"
If a person X is supposed to pay Y money to the others, then print "X owes Y"
If a person X has no dues, then print "X neither owes nor is owed"

Constraints:

 1  ≤ T ≤ 10 
 2  ≤ N ≤ 50 
 1 ≤ Q ≤ 50  
 1 ≤ M ≤ N-1 
 1 ≤ length of each name ≤ 10  
 1 ≤ all amounts ≤ 1000 

Scoring:

 2 ≤ N ≤ 5, 1 ≤ Q ≤ 5 : (30 pts)
 2 ≤ N ≤ 10, 1 ≤ Q ≤ 10 : (30 pts)
Original Constraints : (40 pts)

SAMPLE INPUT
1
4 2
Alice
Bob
Daniel
Mike
Bob
97
1
Alice
Mike
24
2
Alice
Bob

SAMPLE OUTPUT
Alice owes 56
Bob is owed 40
Daniel neither owes nor is owed
Mike is owed 16

Explanation

After the first transaction, Bob pays 97 for Alice and himself. The share will have to divided as 49 for Bob and 48 for Alice. 
ALICE: Expenses = 48, Paid = 0 
BOB: Expenses = 49, Paid = 49

After the second transaction, Mike spends 24 on Alice, Bob and himself. The share will have to divided equally. So now, 
ALICE:  Expenses = 48+8 , Paid = 0  
BOB:  Expenses = 49+8, Paid = 97  
MIKE:  Expenses = 8, Paid = 24

Thus finally,
ALICE has to pay 56.
BOB will get back 97-49-8 = 40.
MIKE will get back 16.
DANIEL has no dues.

Source: hackerearth | Difficulty: EASY
Tags: Data structures

Implementation


Solutions:
import sys
for _ in range(eval(input())):
	n,q=list(map(int,sys.stdin.readline().split()))
	keys=[]
	vlaues = []
	for i in range(n):
		s=str(input())
		keys.append(s)
		vlaues.append(0)
	dicti = dict(list(zip(keys,vlaues)))
	owed = dicti.copy()
	for k in range(q):
		st=input()
		fare = int(input())
		ab = owed[st]
		owed[st] = fare+ab
		num = int(input())
		aa = fare/(num+1)
		fare = fare -aa*num
		ac = dicti[st]
		dicti[st]  = ac+fare
		for j in range(num):
			ss=input()
			ad = dicti[ss]
			dicti[ss]  = ad+aa	
	for k in keys:
		mm = owed[k]-dicti[k]
		if(mm>0):
			print(k,"is owed",mm)
		if(mm == 0):
			print(k,"neither owes nor is owed")
		if(mm<0):
			print(k,"owes",abs(mm))


#print dicti
#print owed


tc = eval(input())

for o in range(tc):
	n, q = list(map(int, input().split()))

	p = [0]*n
	pr = {}
	for i in range(n):
		p[i] = input()
		pr[p[i]] = 0

	for i in range(q):
		paid_by = input()
		amt = eval(input())
		shared = eval(input())

		pp = amt/(shared+1)
		pr[paid_by] += shared*pp

		for j in range(shared):
			ow = input()
			pr[ow] += (-pp)
		# print pr

	for k in p:
		if pr[k] < 0:
			print("{} owes {}".format(k, -pr[k]))
		elif pr[k] > 0:
			print("{} is owed {}".format(k, pr[k]))
		else:
			print("{} neither owes nor is owed".format(k))

	# print pr


noOfTestCases = int(input())

def summary(porder, persons, transactions):
	for t in transactions:
		persons[t['payee']] += (t['amount'] / len(t['paidTo'])) * len(t['paidTo'])
		for p in t['paidTo']:
			persons[p] -= (t['amount'] / len(t['paidTo']))
	
	for personName in porder:
		if(persons[personName] > 0):
			print(personName + " is owed " + str(persons[personName]))	
		elif(persons[personName] < 0):
			amount = abs(persons[personName])
			print(personName + " owes " + str(amount))
		else:
			print(personName + " neither owes nor is owed")


for caseNo in range(1, noOfTestCases + 1):
	noOfPersons, noOfTransactions = input().split(" ")
	noOfPersons, noOfTransactions = int(noOfPersons), int(noOfTransactions)
	persons = {}
	porder = []
	for pno in range(1, noOfPersons + 1):
		p = input()
		persons[p] = 0
		porder.append(p)
		
	transactions = []
	
	for tno in range(1, noOfTransactions + 1):
		transaction = {}
		transaction['payee'] = input()
		transaction['amount'] = int(input())
		splitCount = int(input())
		
		transaction['paidTo'] = []
		
		for s in range(1, splitCount + 1):
			transaction['paidTo'].append(input())
		
		transaction['paidTo'].append(transaction['payee'])
		
		transactions.append(transaction)
	
	summary(porder, persons, transactions)


def update(name, expense, paid):
	for person in gds:
		if person['name'] == name:
			person['expense'] += expense
			person['paid'] += paid
			return


t = int(input())
for _ in range(t):
	n, q = list(map(int, input().split()))
	gds = []
	for name in range(n):
		tmp = input()
		gds.append({"name": tmp, "expense": 0, "paid": 0})

	for  tr in range(q):
		tmp_name = input()
		tmp_paid = int(input())
		sharers = int(input())
		tmp_expense = int(tmp_paid/(sharers+1))
		tmp_expense_payer = tmp_paid - tmp_expense*sharers
		update(tmp_name, tmp_expense_payer, tmp_paid)
		for  sharer in range(sharers):
			tmp_name = input()
			update(tmp_name, tmp_expense, 0)

	for person in gds:
		tp = person['paid'] - person['expense']
		if(tp > 0):
			print("%s is owed %r"%(person['name'], tp))
		elif tp < 0:
			print("%s owes %r"%(person['name'], -tp))
		else:
			print("%s neither owes nor is owed"%(person['name']))


from collections import OrderedDict
t=int(input())
for _ in range(t):
	n,q=list(map(int,input().split()))
	expenses=OrderedDict()
	for N in range(n):
		name=input()
		expenses[name]=[0,0]
	for Q in range(q):
		kid=input()
		amt=int(input())
		count=int(input())
		dup=count+1
		expenses[kid][1]+=amt
		expenses[kid][0]+=(amt/dup+amt%dup)
		for i in range(count):
			temp=input()
			expenses[temp][0]+=(amt/dup)
	for key in expenses:
		diff=expenses[key][1]-expenses[key][0]
		if diff==0:
			print('%s neither owes nor is owed'%key)
		elif diff>0:
			print('%s is owed %d'%(key,diff))
		else:
			print('%s owes %d'%(key,-diff))
			


def readOutPutCase():
	inputString = input().split()
	countName = int(inputString[0])
	countTrans = int(inputString[1])
	namesList = []
	while(countName > 0):
		countName -= 1
		namesList.append(input())
	transList = []
	while(countTrans > 0):	
		countTrans -= 1
		transList.append(readTransaction())
	processTransList(namesList,transList)

def readTransaction():
	transDict = {}
	paid_by = input()
	amount = int(input())
	memberCount = int(input())
	transNamesList = []
	while (memberCount > 0):
		memberCount -= 1
		transNamesList.append(input())

	transDict.update({"paid_by":paid_by, "amount":amount, "members":transNamesList})
	return transDict

def processTransList(namesList,transList):
	outDict = {}
	for name in namesList:
		outDict.update({name:0})
	for trans in transList:
		members = len(trans["members"]) + 1
		if trans["amount"]%members != 0:
			trans["amount"] -= trans["amount"]%members
		owed = trans["amount"]/members
		outDict[trans["paid_by"]] += (trans["amount"]-owed)
		for member in trans["members"]:
			outDict[member] -= owed
	printOutput(namesList,outDict)

def printOutput(namesList,outDict):
	for name in namesList:
		if int(outDict[name]) < 0:
			print(name + " owes " + str(abs(outDict[name])))
		elif int(outDict[name]) == 0:
			print(name + " neither owes nor is owed")
		elif int(outDict[name]) > 0:
			print(name + " is owed " + str(abs(outDict[name])))

	
tests = int(input())
while(tests > 0):
	tests -= 1
	readOutPutCase()


from collections import defaultdict
T=eval(input())
for i in range(T):
	N,Q=list(map(int,input().split()))
	names={}
	name_list=[]
	for i in range(N):
		name=input()
		name_list.append(name)
		names.setdefault(name, [])
	for i in range(Q):
		name_paid=input()
		amt_paid=eval(input())
		M=eval(input())
		share_amt=amt_paid/(M+1)
		extra=amt_paid%(M+1)
		x=share_amt+extra
		names[name_paid].append(amt_paid)
		names[name_paid].append(-x)
		for i in range(M):
			person=input()
			names[person].append(-share_amt)
	for name in name_list:
		total_share=0
		expenses=names[name]
		total_share=sum(expenses)
		if total_share > 0:
			print('{0} is owed {1}'.format(name,total_share))
		elif total_share < 0:
			print('{0} owes {1}'.format(name,-total_share))
		else:
			print('{0} neither owes nor is owed'.format(name))


import sys
for _ in range(eval(input())):
	n,q=list(map(int,sys.stdin.readline().split()))
	keys=[]
	vlaues = []
	for i in range(n):
		s=str(input())
		keys.append(s)
		vlaues.append(0)
	dicti = dict(list(zip(keys,vlaues)))
	owed = dicti.copy()
	for k in range(q):
		st=input()
		fare = int(input())
		ab = owed[st]
		owed[st] = fare+ab
		num = int(input())
		aa = fare/(num+1)
		fare = fare -aa*num
		ac = dicti[st]
		dicti[st]  = ac+fare
		for j in range(num):
			ss=input()
			ad = dicti[ss]
			dicti[ss]  = ad+aa	
	for k in keys:
		mm = owed[k]-dicti[k]
		if(mm>0):
			print(k,"is owed",mm)
		if(mm == 0):
			print(k,"neither owes nor is owed")
		if(mm<0):
			print(k,"owes",abs(mm))


#print dicti
#print owed


t = int(input())
def add_amount(split, name, add):
	split[name] -=amount%(np+1) + add    



while t>0:
	t-=1
	n, q = list(map(int, input().split()))
	split = {}
	l = []
	while n>0:
		n-=1
		name = input()
		split[name]=0
		l.append(name)
	while q>0:
		q-=1
		name = input()
		amount = int(input())
		np = int(input())
		add = amount/(np+1)
		add_amount(split,name, add)
		split[name] += amount
		for i in range(np):
			name = input()
			split[name] -= add    
	for name in l:
		a = split[name]
		if a < 0:
			print(name+" owes "+str(-a))
		elif a>0:
			print(name +" is owed "+str(a))
		else:
			print(name +" neither owes nor is owed")
	


def main():
	tc=int(input())
	while(tc):
		info=list(map(int,input().split()))
		n=info[0]
		q=info[1]
		dic={}
		g=0
		ll=['f']*n
		for i in range(n):
			name=input()
			ll[g]=name
			dic.update({name:0})
			g+=1
		for j in range(q):
			name=input()
			amt=int(input())
			k=int(input())
			k=k
			dic[name]+=amt-(amt/(k+1) +amt%(k+1))
			for l in range(k):
				name=input()
				dic[name]-=(amt/(k+1))
		#print dic
		for name in ll:
			if dic[name]>0:
				st=name+" is owed"
				print(st,dic[name])
			elif dic[name]<0:
				st=name+" owes"
				print(st,-dic[name])
			else:
				st=name+" neither owes nor is owed"
				print(st)
		tc-=1
main()


t = int(input())

for i in range(t):

	n ,q = [int(x) for x in input().split()]
	names = {}
	act = {}
	check = []
	for j in range(n):
		tmp = input()
		names[tmp]= 0
		#print names
		#print "Hi"
		act[tmp]= 0
		check.append(tmp)
	for k in range(q):
		nm = input()
		amt = int(input())
		num = int(input())
		div = amt/(num+1)
		#print "Here"
		names[nm] = names[nm]+div+(amt%(num+1))
		act[nm] += amt
		for j in range(num):
			names[input()] += div
	#temp = []
	#for l in names.keys():
		#temp.append(l)
	#temp.sort()
	for m in check:
		if names[m] == act[m]:
			print(m , "neither owes nor is owed")
		elif names[m]>act[m]:
			print(m , "owes" , (names[m]-act[m]))
		else:
			print(m , "is owed" , (act[m]-names[m]))


t=eval(input(''))
cnt=0


while int(t)>int(cnt):
	d={}
	n_person,q_transaction=input('').split(' ')
	tourist_name=[]
	for i in range(int(n_person)):
		tourist_name.append(str(input('')))
		d[tourist_name[i]]=[0,0]#expense,paid

	for j in range(int(q_transaction)):
		payee_name=str(input(''))#who paid for transaction
		payee_amount=int(input(''))#amount paid in transaction
		payee_divide=int(input(''))#hw many person to divide including payee
		divide_list=[]
		for k in range(int(payee_divide)):
			divide_list.append(str(input('')))#name of other than payee
		#print divide_list
		amnt_to_share =int(payee_amount/(payee_divide+1))
		if (amnt_to_share*(payee_divide+1))==payee_amount:
			other_share=amnt_to_share
			payee_share=amnt_to_share
		else:
			other_share=amnt_to_share
			payee_share=(amnt_to_share+(payee_amount-(amnt_to_share*int(payee_divide+1))))

		for l in range(len(divide_list)):
			d[str(divide_list[l])][1]+=int(other_share)
		d[str(payee_name)][0]+=int(payee_amount)
		d[str(payee_name)][1]+=int(payee_share)
	#print d
	for i in range(int(n_person)):
		if (d[tourist_name[i]][0]-d[tourist_name[i]][1])<0:
			print(str(tourist_name[i])+" owes "+str(abs(d[tourist_name[i]][0]-d[tourist_name[i]][1])))
		else:
			if (d[tourist_name[i]][0]-d[tourist_name[i]][1])>0:
				print(str(tourist_name[i])+" is owed "+str(abs(d[tourist_name[i]][0]-d[tourist_name[i]][1])))
			if (d[tourist_name[i]][0]-d[tourist_name[i]][1])==0:
				print(str(tourist_name[i])+" neither owes nor is owed")

	
	t-=1
	


from collections import OrderedDict
t=int(input())
for _ in range(t):
	n,q=list(map(int,input().split()))
	expenses=OrderedDict()
	for N in range(n):
		name=input()
		expenses[name]=[0,0]
	for Q in range(q):
		kid=input()
		amt=int(input())
		count=int(input())
		dup=count+1
		expenses[kid][1]+=amt
		expenses[kid][0]+=(amt/dup+amt%dup)
		for i in range(count):
			temp=input()
			expenses[temp][0]+=(amt/dup)
	for key in expenses:
		diff=expenses[key][1]-expenses[key][0]
		if diff==0:
			print('%s neither owes nor is owed'%key)
		elif diff>0:
			print('%s is owed %d'%(key,diff))
		else:
			print('%s owes %d'%(key,-diff))
			


'''
# Read input from stdin and provide input before running code

name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
from collections import OrderedDict
for i in range(eval(input())):
	n,q=list(map(int,input().split()))
	d=OrderedDict()
	while n>0:
		n-=1
		x=input()
		d[x]=0
		#print d
	while q>0:
		q-=1
		o=input()
		amt=eval(input())
		p=eval(input())
		u=amt/(p+1)
		d[o]-=amt
		d[o]+=(u+amt-u*(p+1))
		while p>0:
			p-=1
			r=input()
			d[r]+=u
	k=list(d.keys())
	for i in k:
		if d[i]>0:
			print(i+" owes "+str(d[i]))
		elif d[i]<0:
			print(i+" is owed "+str(d[i]*-1))
		else:
			print(i+" neither owes nor is owed ")
		
	



from collections import Counter
def share_the_fare():
	tmp = input().split()
	N, Q = int(tmp[0]), int(tmp[1])

	transactions = Counter()
	persions = []

	# input persions name
	for i in range(N):
		persions.append(input())

	# input transaction details
	for j in range(Q):
		p = input()
		amount = eval(input())
		M = eval(input())

		# dividing amount
		famount = amount / (M+1)
		ramount = amount % (M+1)

		transactions[p] -= (amount - (famount + ramount))

		for _m in range(M):
			transactions[input()] += famount

	for p in persions:
		if transactions[p] < 0:
			print("%s is owed %s"%(p,abs(transactions[p])))
		elif transactions[p] > 0:
			print("%s owes %s"%(p, abs(transactions[p])))
		elif transactions[p] == 0:
			print("%s neither owes nor is owed"%p) 

T = eval(input())

for _t in range(T):
	share_the_fare()
	
	
	
	
	


T = int(input())
for _ in range(T) :
	N,Q = list(map(int,input().split()))
	names = [str(input().strip()) for i in range(N)]
	D = dict([name,{'E':0,'P':0}] for name in names)
	#print D
	for trx in range(Q) :
		payer = str(input().strip())
		amt = int(input().strip())
		M = int(input().strip())
		payee_amt = amt/(M+1)
		payer_amt = amt - payee_amt*M
		
		D[payer]['P']+=amt
		D[payer]['E']+=payer_amt
		for p in range(M) :
			payee = str(input().strip())
			D[payee]['E']+=payee_amt
			#print payee,D
	for name in names :
		diff = D[name]['E'] - D[name]['P']
		if diff == 0 :
			print(name,"neither owes nor is owed")
		elif diff < 0 : 
			print(name,"is owed",diff*(-1))
		else :
			print(name,"owes",diff)


import sys
test = int(input())
for x in range(test):
	Number,query=list(map(int,sys.stdin.readline().split()))
	key=[]; vlaue = []
	for i in range(Number):
		string=input()
		key.append(string)
		vlaue.append(0)
	owes = dict(list(zip(key,vlaue)))
	owed = owes.copy()
	for i in range(query):
		strinput=str(input())
		fare = int(input())
		present = owed[strinput]
		owed[strinput] = fare+present
		number = int(input())
		share = fare/(number+1)
		fare = fare -share*number
		rem = owes[strinput]
		owes[strinput]  = rem+fare
		for j in range(number):
			strr=str(input())
			past = owes[strr]
			owes[strr]  = share+past	
	for keys in key:
		amount = owed[keys]-owes[keys]
		if(amount>0):
			print(keys,"is owed",amount)
		if(amount == 0):
			print(keys,"neither owes nor is owed")
		if(amount<0):
			print(keys,"owes",abs(amount))


tc=int(input())
while tc:
	tc=tc-1
	N,Q=list(map(int,input().split()))
	persons=[]
	for i in range(N):
		persons.append(input())
	#print 'N,Q,persons:',N,Q,persons
	Expenses={}
	Paid={}
	for I in persons:
		Expenses[I]=0
		Paid[I]=0
	#print 'Expenses,Paid:',Expenses,Paid
	for i in range(Q):
		person_paid=input()
		amount=eval(input())
		no_of_person=eval(input())
		q_persons=[person_paid]
		for j in range(no_of_person):
			q_persons.append(input())
		#print 'person_paid,amount,no_of_person,q_persons:',person_paid,amount,no_of_person,q_persons

		no_of_person+=1
		Paid[person_paid]+=amount
		
		for ab in q_persons:
			Expenses[ab]+=amount/no_of_person            
		
		Expenses[q_persons[0]]+=amount%no_of_person

		#print 'Expenses,Paid:',Expenses,Paid


	for A in persons:
		if Expenses[A]>Paid[A]:
			#print A,' has to pay ',Expenses[A]-Paid[A]
			print(A,'owes',Expenses[A]-Paid[A])
		elif Expenses[A]<Paid[A]:
			#print A,' will get back ',Paid[A]-Expenses[A]
			print(A,'is owed',Paid[A]-Expenses[A])
		else:
			#print A,' has no dues'
			print(A,'neither owes nor is owed')
			


		


'''
# Read input from stdin and provide input before running code

name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T = int(input())

for i in range(T):
	temp = input().split(' ')
	N = int(temp[0])
	Q = int(temp[1])
	per = {}
	perlist = []
	for j in range(N):
		person = input()
		per[person] = [0,0]
		perlist.append(person)
	for j in range(Q):
		person = input()
		paid = int(input())
		per_inv = int(input())
		per_list = []
		for k in range(per_inv):
			per_list.append(input())
		per[person][0] += paid/(len(per_list)+1) + paid%(len(per_list)+1)
		per[person][1] += paid
		# per[person] += paid - paid/(len(per_list)+1)
		for k in per_list:
			per[k][0] += paid/(len(per_list)+1)
			per[k][1] += 0
	for p in perlist:
		if per[p][1]-per[p][0]<0:
			print(p,'owes',abs(per[p][1]-per[p][0]))
		elif per[p][1]-per[p][0]>0:
			print(p,'is owed',per[p][1]-per[p][0])
		else:
			print(p,'neither owes nor is owed')


'''
# Read input from stdin and provide input before running code

name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T = int(input())

for i in range(T):
	temp = input().split(' ')
	N = int(temp[0])
	Q = int(temp[1])
	per = {}
	perlist = []
	for j in range(N):
		person = input()
		per[person] = [0,0]
		perlist.append(person)
	for j in range(Q):
		person = input()
		paid = int(input())
		per_inv = int(input())
		per_list = []
		for k in range(per_inv):
			per_list.append(input())
		per[person][0] += paid/(len(per_list)+1) + paid%(len(per_list)+1)
		per[person][1] += paid
		# per[person] += paid - paid/(len(per_list)+1)
		for k in per_list:
			per[k][0] += paid/(len(per_list)+1)
			per[k][1] += 0
	for p in perlist:
		if per[p][1]-per[p][0]<0:
			print(p,'owes',abs(per[p][1]-per[p][0]))
		elif per[p][1]-per[p][0]>0:
			print(p,'is owed',per[p][1]-per[p][0])
		else:
			print(p,'neither owes nor is owed')


def update(name, expense, paid):
	for person in gds:
		if person['name'] == name:
			person['expense'] += expense
			person['paid'] += paid
			return


t = int(input())
for _ in range(t):
	n, q = list(map(int, input().split()))
	gds = []
	for name in range(n):
		tmp = input()
		gds.append({"name": tmp, "expense": 0, "paid": 0})

	for  tr in range(q):
		tmp_name = input()
		tmp_paid = int(input())
		sharers = int(input())
		tmp_expense = int(tmp_paid/(sharers+1))
		tmp_expense_payer = tmp_paid - tmp_expense*sharers
		update(tmp_name, tmp_expense_payer, tmp_paid)
		for  sharer in range(sharers):
			tmp_name = input()
			update(tmp_name, tmp_expense, 0)

	for person in gds:
		tp = person['paid'] - person['expense']
		if(tp > 0):
			print("%s is owed %r"%(person['name'], tp))
		elif tp < 0:
			print("%s owes %r"%(person['name'], -tp))
		else:
			print("%s neither owes nor is owed"%(person['name']))


for _ in range(int(input())):
	n,q = list(map(int,input().split()))
	l = []
	t = [0]*n
	for i in range(n):
		l.append(input())
	for i in range(q):
		spender = input()
		amt = int(input())
		p = int(input())
		share = amt/(p+1)
		t[l.index(spender)] += p * share
		for o in range(p):
			#ppl = raw_input()
			t[l.index(input())] -= share
	for i in range(len(t)):
		if t[i]==0:
			print(l[i] + " neither owes nor is owed")
		elif t[i]<0:
			print(l[i] + " owes " + str(abs(t[i])))
		else:
			print(l[i] + " is owed " + str(t[i]))


def main():
	TestCases = int(input())
	line = ''
	arr = []
	N = 0
	Q = 0
	for i in range(0,TestCases):
	  line = input()
	  arr =  line.split()
	  N = int(arr[0])
	  Q = int(arr[1])

	  hash_list = {}
	  cash_list = []
	  name_list = []
	  for i in range(0,N):
	  	cash_list.append(0)


	  for i in range(0,N):
	  	names = input()
	  	hash_list[names] = i
	  	name_list.append(names)

	  for i in range(0,Q):
	  	paid = input()
	  	amount = int(input()) 
	  	count = int(input())
	  	people = count + 1
	  	cash_list[hash_list[paid]] = cash_list[hash_list[paid]] + (amount - (amount%people) - (amount/people))

	  	for i in range(0,count):
	  		person = input()
		  	cash_list[hash_list[person]] = cash_list[hash_list[person]] - (amount/people)

	  for i in range(0,N):
	  	if cash_list[hash_list[name_list[i]]] > 0:
	  		print(name_list[i] + " is owed " + str(cash_list[hash_list[name_list[i]]]))
	  	elif cash_list[hash_list[name_list[i]]] < 0:
	  		print(name_list[i] + " owes " + str(-1 * cash_list[hash_list[name_list[i]]]))
	  	else:
	  		print(name_list[i] + " neither owes nor is owed")


if __name__ == '__main__':
	main()


import sys
test = int(input())
for x in range(test):
	Number,query=list(map(int,sys.stdin.readline().split()))
	key=[]; vlaue = []
	for i in range(Number):
		string=input()
		key.append(string)
		vlaue.append(0)
	owes = dict(list(zip(key,vlaue)))
	owed = owes.copy()
	for i in range(query):
		strinput=str(input())
		fare = int(input())
		present = owed[strinput]
		owed[strinput] = fare+present
		number = int(input())
		share = fare/(number+1)
		fare = fare -share*number
		rem = owes[strinput]
		owes[strinput]  = rem+fare
		for j in range(number):
			strr=str(input())
			past = owes[strr]
			owes[strr]  = share+past	
	for keys in key:
		amount = owed[keys]-owes[keys]
		if(amount>0):
			print(keys,"is owed",amount)
		if(amount == 0):
			print(keys,"neither owes nor is owed")
		if(amount<0):
			print(keys,"owes",abs(amount))


def mod(x):
	if x >= 0:
		return x
	else:
		return -x
T = int(input())
while(T!=0):
	N,Q = list(map(int,input().strip().split(" ")))
	people_dict = {}
	name_list = []
	for i in range(N):
		name = input().strip()
		people_dict[name]=0
		name_list.append(name)

	for i in range(Q):
		person_name = input().strip()
		amount_paid = int(input().strip())
		#people_dict[raw_input().strip()] += int(raw_input().strip())
		people_dict[person_name] += amount_paid
		#print people_dict
		num_of_people = int(input().strip()) 
		people_dict[person_name] -= amount_paid/(num_of_people+1)+(amount_paid)%(num_of_people+1)
		#print "number of people",num_of_people
		for j in range(num_of_people):
			person_owe = input().strip()
			#print "people_owe",people_owe
			people_dict[person_owe] -= amount_paid/(num_of_people+1)
			#print "inside inner loop",people_dict
	#keys = sorted(people_dict.keys())	
	"""

	for key,value in people_dict.iteritems():

		if value < 0:
			print key+" owes "+str(value)
		elif value > 0:
			print key+" is owed "+str(value)
		else:
			print key+" neither owes nor is owed"
	"""
	for key in name_list:
		if people_dict[key] < 0:
			print(key+" owes "+str(mod(people_dict[key])))
		elif people_dict[key] > 0:
			print(key+" is owed "+str(mod(people_dict[key])))
		else:
			print(key+" neither owes nor is owed")

	T=T-1