My opinion: You're making this overly complicated.
Think of it as a "pool" of money, and lose the relationships altogether:
Instead of:
- Mike owes John 100
- John owes Rachel 200
- Mike owes Rachel 400
The algorithm only has to think:
- Mike owes 100
- John is owed 100
- John owes 200
- Rachel is owed 200
- Mike owes 400
- Rachel is owed 400
Netting this:
- Mike owes 500
- John owes 100
- Rachel is owed 600
Separate this into a list of "givers" and "receivers". Each giver on the list will go through the list of receivers, giving each receiver what they need until the giver has payed up. When a receiver receives everything they need, they go off the list.
Later Edit
As other posters have observed, this simplifies the problem. However, there might be an optimal ordering of the "givers" and "receivers" lists, but we haven't yet identified a straightforward way to determine this ordering.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…