因此,我正在尝试解决Python中的问题,并且能够生成形式的矩阵:
[
[ 0, 0, 0, 1, 1, 1 ],
[ 0, 0, 1, 0, 1, 1 ],
[ 0, 1, 0, 0, 0, 1 ],
[ 1, 0, 0, 0, 1, 1 ],
[ 1, 1, 0, 1, 0, 0 ],
[ 1, 1, 1, 1, 0, 0 ],
]
这只是数组数组。矩阵是一个方形矩阵,其对角线总是为0,因为它实际上代表了两个实体之间的兼容性。例如,实体0与第一列中1代表的实体3、4和5兼容。矩阵沿对角线镜像,因为如果实体1与实体3兼容,那么实体3也将与条目1兼容。
现在,我本质上想要做的就是找到一种最大数量的兼容实体数量,而无需重复配对, 。例如,如果实体0已与实体3配对,则不应将其与实体4配对。但是,如果实体3具有另一个兼容实体,但实体4却没有,那么实体0应该与实体4配对,而不是实体4 3。
最终目标是找出将保持不配对的实体数量。我可能会强迫这样的解决方案,但是由于它比编程问题更像是一个数学问题,所以我想知道是否有一种有效的方法可以解决。
So I am trying to solve a problem in python and I am able to generate a matrix of the form:
[
[ 0, 0, 0, 1, 1, 1 ],
[ 0, 0, 1, 0, 1, 1 ],
[ 0, 1, 0, 0, 0, 1 ],
[ 1, 0, 0, 0, 1, 1 ],
[ 1, 1, 0, 1, 0, 0 ],
[ 1, 1, 1, 1, 0, 0 ],
]
Which is just an array of arrays. The matrix is a square matrix whose diagonal is always going to be 0 because it essentially represents compatibility between two entities. For example, entity 0 is compatible with entity 3, 4, and 5, represented by 1's in the first column. The matrix is mirrored along the diagonal because if entity 1 is compatible with entity 3 then entity 3 will also be compatible with entry 1.
Now what I essentially want to do is find a way that maximum number of compatible entities get paired up, without repetition. For example, if entity 0 has been paired with entity 3, then it should not be paired up with entity 4. However if entity 3 has another compatible entity but entity 4 does not, then entity 0 should be paired with entity 4 and not entity 3.
The end goal is to find out the number of entities that would remain unpaired. I could probably brute force such a solution but since its more of a math problem than a programming one, I would like to know if there is an efficient way of going about it.
发布评论
评论(1)
看来您拥有的是 ateackency matrix 无方向的图形。图由节点之间的节点和边缘组成。您的问题可以总结为在a
您首先从邻接矩阵构建图对象;然后致电找到最大的基数匹配。它实现 edmonds's edmonds's blossom algorithm 。
这将输出最大的基数匹配:
从那里,如果您想找到无与伦比的节点的数量,则可以找到节点和匹配的节点之间的区别:
输出:输出:
It appears what you have is an adjacency matrix of an undirected graph. Graphs consist of nodes and edges between the nodes. Your problem can be summarized as finding the number of unmatched nodes in a maximum cardinality matching. There's networkx API in Python that deals with graphs and if you're willing to use it, the problem becomes very simple.
You first build a graph object from the adjacency matrix; then call
max_weight_matching
to find the maximum cardinality matching. It implements Edmonds' blossom algorithm.this outputs the maximum cardinality matching:
From there, if you want to find the number of nodes that are unmatched, you can find the difference between the nodes and the matched nodes:
Output: