Who owes who money optimization

后端 未结 10 1289
暗喜
暗喜 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:17

    This problem may be tackled with the Warshall algorithm.

    for(i=0;i owes[j][i] )
    owes[i][j] -= (owes[i][j] - owes[j][i]), owes[j][i] = 0;
    
    for(k=0;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).

提交回复
热议问题