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
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
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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.
We need to parse problem, design solution. The problem: There are N persons. Q transactions. For each transaction: payer pays amount A. Then there are M other persons among whom the amount is to be split equally (plus the payer? Actually description: "the number of people(other than the person who paid) M between whom this amount is to be split." So M is the count of others, not including the payer. Also, the amount is split among the payer and those M people? The problem says: "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." And "the person who paid the bill will have to bear the little extra cost himself on each bill." So amount is split equally among all participants (including payer) but with integer division: each person (including payer) should owe an equal share? Actually careful: "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." So the interpretation: For each transaction, the total amount A is to be divided equally among all participants (payer + M others). However, because division may not be integral, the payer will pay the extra amount such that each other person pays exactly floor(A / (M+1))? Or each person's share is A/(M+1), but the payer pays the whole amount, so the net for the payer is they paid A, but they are responsible for a share of A/(M+1). So effectively, each participant (including payer) owes share = A // (M+1) (integer division) and the payer covers the remainder. That is typical splitting.
But need to confirm with example: First transaction: Bob pays 97, M=1 (Alice). So participants = Bob + Alice = 2. Share = 97/2 = 48.5. Payer bears extra: So Alice's share = 48, Bob's share = 49? Actually they said: "share will have to divided as 49 for Bob and 48 for Alice." That matches: each participant owes integer share: floor(97/2)=48, but the sum of 48+48=96, remainder=1, which is covered by payer, making Bob's effective expense = 48+1=49. So yes.
Second transaction: Mike pays 24, M=2 (Alice, Bob). Participants = Mike + Alice + Bob = 3. Share = 24/3=8 exactly. So each owes 8. So Mike's expense=8, Alice's expense=8, Bob's expense=8. The amount paid by Mike is 24, so Mike net pays 24-8=16 more, which will be returned.
Thus net: For each person, we track total amount they paid (paid_by) and total amount they owe (expenses share). Then final due = paid - owed. If positive, they are owed that amount from others (i.e., net credit). If negative, they owe that amount (net debit). If zero, neither.
But careful: In a transaction, participants are exactly the payer and the M listed others. There's no extra people like "Daniel" in first transaction. So Daniel not involved, owes nothing and paid nothing.
We must compute final net for each person: net = total_paid - total_owed. But careful: "owed" here is the share they are supposed to pay (their expense). So if net > 0, they are owed net (others owe them that much). If net < 0, they owe -net.
Now in the output: "X is owed Y" for net positive, "X owes Y" for net negative (i.e., owes Y), "X neither owes nor is owed" for zero.
But note: In the sample output: Alice owes 56, Bob is owed 40, Mike is owed 16. Let's compute with above:
For each participant (including payer): owed[participant] += share_per_person.
But careful: Actually the payer also owes share_per_person? In the net calculation, yes, they owe that share. They paid the whole amount, so their paid gets incremented by amount. So net effect: net[ payer ] += amount (paid) - share_per_person (owed) - maybe extra? But we can separately add share to owed for all participants. The payer will also get share added to owed.
But also note that there might be remainder. That remainder effectively increases the payer's expense beyond share. However, since we record owed = share_per_person for payer as well, but the payer actually paid amount, which includes remainder. So the net difference: paid - owed = amount - share_per_person. For other participants, paid = 0, owed = share_per_person, so net = -share_per_person.
But in the sample, Bob's owed share was 49, not share_per_person (48). They set Bob's owed to 49. How did they get 49? They effectively gave Bob the extra remainder. So to get Bob's owed=49, we need to add remainder to his owed only, not to others. That suggests we should compute:
For each other participant (the M names): owed[other] += share.
For payer: owed[payer] += share + remainder.
Because payer bears the extra cost. That yields Bob owed = 49 (48+1) as per sample. And for others, they only owe the share. Then paid[payer] += amount.
Alternatively, we could treat all participants' owed as share, and then separately add remainder to payer's owed. That's fine.
If we added share to payer as well, then we would have to adjust for remainder: perhaps do owed[payer] += share (like others) and then later add remainder to his owed? That yields same: payer owed = share + remainder. So it's good.
But if we added share to all participants (including payer) and then added remainder to payer, then we must be careful not to double count. So best: compute share and remainder. Then for each of the M others: owed[other] += share. Then for payer: owed[payer] += share + remainder. Also paid[payer] += amount.
Alternatively, we can update owed for all participants as share, then add remainder to payer's owed. That's similar.
Now the question: In transaction where M people, it's said "M lines follow each containing the names of the people between whom this amount is to be split." It says "between whom this amount is to be split." It means the amount is split among the payer and these M persons. So the participants are payer + those M. So that's what we did.
Edge cases: M could be 0? Constraint says M ≥ 1? Actually "1 ≤ M ≤ N-1" So M at least 1. So there is always at least one other participant. So total participants >=2.
But also note: The names given in the list of M others are guaranteed to be among the N persons? Probably yes, as they are present. We can assume valid.
Now we must output for each name in the order they appear in the input? The problem says "print N lines containing the final dues for each person in the following manner". In sample, output order is Alice, Bob, Daniel, Mike, which is same as input order. So we should output in the order given in the input list.
Thus we can store names in an array, and compute net for each.
Now we need to produce output exactly: "Alice owes 56" etc. Note spaces. No trailing spaces.
Now scoring: We just need to implement straightforwardly.
Complexities: T up to 10, N up to 50, Q up to 50, M up to N-1. So trivial.
Now confirm with sample. Works.
Potential pitfalls: reading input lines. There may be blank lines? In the sample, transactions are separated by lines. We need to be careful with reading lines after reading integers. Use input() each time, but note that after reading Q, we have names lines (N lines). Then for each transaction, we have payer line, amount line (convert to int), M line (convert to int), then M names. So it's simple.
Now ensure we handle possible whitespace. Use strip().
Edge Cases: amount division where remainder !=0. Our method works.
Now final net: net = paid[name] - owed[name]. If net > 0, print f"{name} is owed {net}". If net < 0, print f"{name} owes {-net}". If net == 0, print f"{name} neither owes nor is owed".
Be careful: For net positive, "is owed" is used. For net negative, "owes" used.
Now consider possibility that a person may be involved as payer in some transactions and as participant in others. Our dictionaries need to be initialized for all names.
We'll also use default dict or normal dict with initial zero for each name.
Implementation steps:
Read integer T.
For each test case:
Read line for N and Q. Possibly with extra spaces. Use split.
N = int, Q = int.
Read N names: for i in range(N): name = input().strip()
Create dicts: paid = {name:0 for name in names}, owed = {name:0 for name in names}
After processing all transactions, iterate over names in original order:
net = paid[name] - owed[name]
if net > 0: print(f"{name} is owed {net}")
elif net < 0: print(f"{name} owes {-net}")
else: print(f"{name} neither owes nor is owed")
Possibly print blank line between test cases? Not specified, but sample has only one test case. Typically no blank line between test cases. So just print each test case's outputs as lines. I think no extra blank.
Final nets:
Alice: 0-56 = -56 -> owes 56
Bob: 97-57=40 -> is owed 40
Daniel: 0-0=0 -> neither
Mike: 24-8=16 -> is owed 16
Matches.
All good.
Now about possible large numbers: amount up to 1000, Q up to 50, net may be up to 50000. So fits int.
Now multiple test cases.
One nuance: The names can have uppercase/lowercase, so case-sensitive. We'll keep as given.
Now we need to ensure we treat each transaction independently. Good.
Now implement solve().
But there may be a catch: The problem says "the person who paid the bill will have to bear the little extra cost himself on each bill." That means that the payer's share is the floor division (share) plus remainder. So our method is correct.
Another nuance: Could the same person appear multiple times in M list? Probably not, as distinct people. Input guarantee? It says M lines each containing names; likely distinct.
Now confirm: If M equals number of others present, can be up to N-1.
Edge case: If M = N-1, then all persons are participants? Actually all persons include payer plus others; if M=N-1, then participants are all N people. So that's fine.
Now done.
But wait: The problem description says "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." So M lines follow each containing the names of the people between whom this amount is to be split. So yes.
Now code.
I'll produce a Python solution.
Potential issues: Input reading might have empty lines; but likely not. Use input().strip().
But note: After reading M, we read M names. They may have spaces? Names are single word with alphabets only. So safe.
Now we will produce final answer.
But the question is from code. Let's double-check constraints: T up to 10, N up to 50, Q up to 50. So O(TQN) is fine.
Now code:
def solve():
import sys
data = sys.stdin.read().splitlines()
# But simpler to use input() in loop. Use sys.stdin.
# However, need to manage reading line by line. For simplicity, I'll use sys.stdin.readline.
import sys
input = sys.stdin.readline
T = int(input().strip())
for _ in range(T):
line = input().strip()
while line == '':
line = input().strip()
N, Q = map(int, line.split())
names = []
for i in range(N):
name = input().strip()
while name == '':
name = input().strip()
names.append(name)
paid = {name:0 for name in names}
owed = {name:0 for name in names}
for __ in range(Q):
payer = input().strip()
while payer == '':
payer = input().strip()
amount = int(input().strip())
M = int(input().strip())
others = []
for j in range(M):
other = input().strip()
while other == '':
other = input().strip()
others.append(other)
total = M + 1
share = amount // total
remainder = amount % total
for other in others:
owed[other] += share
owed[payer] += share + remainder
paid[payer] += amount
# After transactions
for name in names:
net = paid[name] - owed[name]
if net > 0:
print(f"{name} is owed {net}")
elif net < 0:
print(f"{name} owes {-net}")
else:
print(f"{name} neither owes nor is owed")
# Optionally print blank line between test cases? Not required.
if name == "main":
solve()
Now check sample:
Input:
1
4 2
Alice
Bob
Daniel
Mike
Bob
97
1
Alice
Mike
24
2
Alice
Bob
Our reading: After reading N and Q, we read 4 names: Alice, Bob, Daniel, Mike. Then first transaction: payer Bob, amount 97, M=1, other Alice. Then second transaction: payer Mike, amount 24, M=2, others Alice, Bob. Works.
Now produce output lines exactly as required.
Potential pitfalls: The sample output has "Alice owes 56" etc. Good.
Now think about case where the same person is payer and also appears in others? Not possible because M are other than payer. So safe.
Now final.
But we should also consider possible trailing newlines or spaces. We'll strip.
Now maybe we need to handle multiple test cases and ensure no extra newline after last test case. Fine.
Now we can also use defaultdict to simplify but not needed.
Now additional nuance: Could there be transactions where the amount is less than total participants? For example amount=3, M=2 (total participants=3), share=1, remainder=0. Works.
If amount=1, M=1, share=0, remainder=1. Then others owe 0, payer owes 1. That is fine: payer pays 1 and bears all cost.
Now test another: Suppose amount=5, M=2, total=3, share=1, remainder=2. Others owe 1 each, payer owes 1+2=3. So total owed: 1+1+3=5. Good.
Thus correct.
Now we are ready.
But maybe there is alternative interpretation: Could it be that the amount is split equally among all participants, and the payer gets the credit of amount paid, while others get debited share? But the remainder is assigned to payer as an expense. That's what we did.
Now we can finalize.
Potential issue: The input might have blank lines between transactions? In sample there is no blank line. But we added while loops to skip empty lines, just in case.
But in standard CodeChef/Hackerearth problems, input does not have blank lines. But it's safe.
Now final answer.
One more check: The output lines should be exactly as described. "neither owes nor is owed" not "neither owes nor owed". In sample: "Daniel neither owes nor is owed". So "neither owes nor is owed". Good.
Now proceed.
But we need to output for each test case. No extra blank line between test cases unless specified. Usually not needed.
Now implement.
I will produce final answer code accordingly.
But the user expects just the code? Usually they'd want the solution. The instruction is "write the code". So provide the code.
Now ensure using sys.stdin and output print.
Now I will produce final message.
```python
import sys
def solve() -> None:
input = sys.stdin.readline
T = int(input().strip())
for _ in range(T):
# read N and Q (skip possible empty lines)
line = input().strip()
while line == '':
line = input().strip()
N, Q = map(int, line.split())
code
# read the N names
names = []
for _ in range(N):
name = input().strip()
while name == '':
name = input().strip()
names.append(name)
# initialise dictionaries
paid = {name: 0 for name in names}
owed = {name: 0 for name in names}
# process Q transactions
for _ in range(Q):
payer = input().strip()
while payer == '':
payer = input().strip()
amount = int(input().strip())
M = int(input().strip())
others = []
for _ in range(M):
other = input().strip()
while other == '':
other = input().strip()
others.append(other)
total = M + 1
share = amount // total
remainder = amount % total
# update owed amounts
for other in others:
owed[other] += share
owed[payer] += share + remainder
# update amount paid by the payer
paid[payer] += amount
# produce output in the original order
for name in names:
net = paid[name] - owed[name]
if net > 0:
print(f"{name} is owed {net}")
elif net < 0:
print(f"{name} owes {-net}")
else:
print(f"{name} neither owes nor is owed")