Arranging the number 1 in a 2d matrix

后端 未结 6 1720
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 17:11

Given the number of rows and columns of a 2d matrix

Initially all elements of matrix are 0

Given the number of 1\'s that should be present in each row

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 17:48

    Hint: one possible solution utilizes Maximum Flow Problem by creating a special graph and running the standard maximum flow algorithm on it.

    If you're not familiar with the above problem, you may start reading about it e.g. here https://en.wikipedia.org/wiki/Maximum_flow_problem

    If you're interested in the full solution please comment and I'll update the answer. But it requires understading the above algorithm.

    Solution as requested:

    Create a graph of r+c+2 nodes.

    Node 0 is the source, node r+c+1 is the sink. Nodes 1..r represent the rows, while r+1..r+c the columns.

    Create following edges:

    • from source to nodes i=1..r of capacity r_i
    • from nodes i=r+1..r+c to sink of capacity c_i
    • between all the nodes i=1..r and j=r+1..r+c of capacity 1

    Run maximum flow algorithm, the saturated edges between row nodes and column nodes define where you should put 1.

    Or if it's not possible then the maximum flow value is less than number of expected ones in the matrix.

提交回复
热议问题