Who owes who money optimization

后端 未结 10 1263
暗喜
暗喜 2020-12-14 02:18

Say you have n people, each who owe each other money. In general it should be possible to reduce the amount of transactions that need to take place. i.e. if X owes Y £4 and

相关标签:
10条回答
  • 2020-12-14 03:02

    I think you need to build a different data structure ( a tree, each time one person is the root node) that will check for each person how many "transaction" can you "kill", than, choose the best one, make the cycle, and rebuild it again.it is not o(N), I Think it's N^2 though, and it will not give you the best result. it is just a strategy.

    0 讨论(0)
  • 2020-12-14 03:17

    This problem may be tackled with the Warshall algorithm.

    for(i=0;i<n;i++)
      for(j=0;j<n;j++)
        if ( i!= j && owes[i][j] > owes[j][i] )
    owes[i][j] -= (owes[i][j] - owes[j][i]), owes[j][i] = 0;
    
    for(k=0;k<n;k++)
     for(i=0;i<n;i++)
      for(j=0;j<n;j++)
      {
    if( k == i || i == j || k == j ) continue;
    if ( owes[j][k] > owes[i][j] )
    {
    int diff = owes[j][k] - owes[i][j]; 
    owes[i][j] = 0;
    owes[i][k ] += diff;
    owes[j][k] -= diff;
    } 
    }
    

    After the algorithm finishes, the total number of transactions required would be the number of positive entries in the owes table.

    I have not verified yet whether the algorithm will work, based on nature of the problem it may work. Solution is O(N^3).

    0 讨论(0)
  • 2020-12-14 03:19

    Nominate one person arbitrarily to be the banker.

    Each other person transfers the sum of all the outgoing transactions minus the incoming transactions (so either deposits or withdraws) to that person.

    There will be a maximum of (n-1) transactions, which is pretty small. It is fast. It is simple.

    Given that everyone who transfers money will have to be involved in a transaction anyway*, it is bounded to be at worst twice the optimal case.**

    * The exception is the banker themselves. A quick optimisation is to ensure the nominated banker is not someone who holds a neutral position.

    ** Explaining my upper bound logic further:

    Suppose the optimal case is A gives $1 to B, and C gives $1 to D, and E is neutral = two transactions.

    Then with this logic, if E is the nominated banker, A gives $1 to E, E gives $1 to B, C gives $1 to E and E gives $1 to D = four transactions.

    With the optimisation, making sure you don't choose a neutral person for banker, select A instead. A gives $1 to B, C gives $1 to A. A gives $1 to D = three transactions.

    0 讨论(0)
  • 2020-12-14 03:21

    Just thinking about it I'd start by looking at each cycle in the directed graph and reducing each edge in the cycle by the value of the minimum edge in the cycle, then remove the minimum edge altogether. Rinse and repeat.

    0 讨论(0)
提交回复
热议问题