What algorithm to use to determine minimum number of actions required to get the system to “Zero” state?

前端 未结 10 656
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 18:25

This is kind of more generic question, isn\'t language-specific. More about idea and algorithm to use.

The system is as follows:

It registers small loans bet

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 19:17

    I found a practical solution which I implemented in Excel:

    • find out who ows the most

    • let that person pay the complete amount he ows to the one who should get the most

    • that makes the first person zero

    • repeat this proces taken into account that one of (n-1) persons has a changed amount

    It should result in a maximum of (n-1) transfers and the nice thing about it is that no one is doing more than one payment. Take the (modified) example of jrandomhacker:

    a=-5 b=25 c=-20 d=3 e=-2 f=-1 (sum should be zero!)

    1. c -> b 20. result: a=-5 b=5 c=0 d=3 e=-2 f=-1

    2. a -> b 5 result: a=0 b=0 c=0 d=3 e=-2 f=-1

    3. e -> d 2 result a=0 b=0 c=0 d=1 e=0 f=-1

    4. f -> d 1

    Now, everyone is satisfied and no one is bothered by making two or more payments. As you can see, it is possible that one person recieves more than one payment (person d in this example).

提交回复
热议问题