求解划分问题的递归回溯算法
嘿,我正在寻求一些帮助来找到一种算法,该算法将正数数组分为 k 个部分,以便每个部分具有(大约)相同的总和......假设我们有
1,2,3,4 ,5,6,7,8,9 en k=3 那么算法应该像这样划分它 1,2,3,4,5|6,7|8,9 元素的顺序不能改变...找到一个贪婪算法很容易,但我正在寻找一个总是返回最佳解决方案的回溯版本...
有人有任何提示吗?
Hey, i'm looking for some help to find an algorithm which divides an array of positive numbers into k-parts so that each part has the (approximately) the same sum ... let's say we have
1,2,3,4,5,6,7,8,9 en k=3 thn the algorithm should partition it like this 1,2,3,4,5|6,7|8,9
the order of the elements cannot be changed ... Finding a greedy algorithm is easy but i'm looking for a backtracking version which always returns the optimal solution ...
Annyone got any hints ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个不使用任何动态数据结构(例如列表)的解决方案。它们完全没有必要,并且实际上会使算法比必要的慢得多。
令 K 为此处的分区数,N 为数组中的元素数。
注意:这是一个 O(nK) 算法。它是次指数的,因为这不相当于一般的 NP 完全划分问题,在这里您正在寻找线性数组的连续段而不是给定总集的任意子集。
Here is a solution that doesn't use any dynamic data structures such as lists. They are totally unnecessary and would in practice make the algorithm much slower than necessary.
Let K be the number of partitions here and N be the number of elements in your array.
Note: this is an O(nK) algorithm. It is sub-exponential because this is not equivalent to the general NP-complete partitioning problem has here you are looking for contiguous segments of a linear array instead of arbitrary subsets of a given total set.
你所说的最优解是什么意思?我相信你的意思是最小化每个分区到最佳分区的距离之和。最佳分区是其元素之和等于总和除分区数的分区。
如果您不介意效率,那么也许这种粗略的方法对您来说已经足够了。我还没有测试该算法来检查其正确性,所以要小心。
What do you mean by optimal solution? I believe you mean the one that minimizes the sum of each partition distance to the optimum partition. The optimum partition would be the partition that it's elements sum is equal to the total sum divided the number of partitions.
If you don't mind about efficiency, then maybe this rough approach is good enough for you. I haven't tested the algorithm to check it's correctness, so be careful.
这是 Javascript 中的递归算法。此函数返回每个工人将分配的总数。假设输入数组 bookLoads 是一个正数数组,您希望将其尽可能公平地划分为 k 个部分(假设在 k 个工作人员中)
这是一个工作小提琴:
https://jsfiddle.net/missyalyssi/jhtk8vnc/3/
Here is a recursive algorithm in Javascript. This function returns the totals that each worker will be assigned. Lets say the input array bookLoads is an array of positive numbers that you want to divide as fairly as possible into k-parts (let's say among k workers)
Here is a working fiddle:
https://jsfiddle.net/missyalyssi/jhtk8vnc/3/