What type of algorithm should i use?

三世轮回 提交于 2019-12-09 11:02:06

问题


Lets say I have four group

A [ 0, 4, 9]

B [ 2, 6, 11]

C [ 3, 8, 13]

D [ 7, 12 ]

Now I need one number from each group(i.e a new group) E [num of A,num of B, num of C, num of D], such that the difference between the maximum num in E and minimum num in E should be possible lowest.What type of problem is this ? which graph algorithm will be better to solve this kind of problem ? Thanks in advance.

P.S : I'm trying to solve this in java and sorry for the unspecified title.

Edit : Finally I've found what I'm actually looking for http://rcrezende.blogspot.in/2010/08/smallest-relevant-text-snippet-for.html


回答1:


  1. Combine contents of every group into a single array. Each element of the array should be a pair of (number, group name).
  2. Sort this array by numbers.
  3. Advance two iterators, one after another. Move first iterator when elements of not every group are between these iterators. Move second iterator when there is an element of each group between these iterators. For details see this question.
  4. Minimum distance between iterators determine optimal resulting group (you only need to drop unneeded elements when there are several representatives of the same group there).

Other algorithm:

  1. Sort elements of each group (if not sorted already).
  2. Put a pair (number, group name) for smallest elements of each group into priority queue (min-heap, priority=number).
  3. Remove smallest element from the queue and replace it with the next element from the same group.
  4. Repeat step 3 until no more elements are left in some group. Calculate max(queue) - min(queue) for each iteration and if it is smaller than any previous value, update the best-so-far resulting group.



回答2:


I think you could do an exhaustive search, with quick termination, it's not as bad as it seems.

For example if you pick a number from A and B, you can pick two numbers from C which are the closest to those two numbers, using any other number cannot yield better results.

  • For each element of A: call it a, you are looking for a numbers which are close to interval (a,a)
  • Now for each group pick the closest numbers (you can do it with binary search). Now you have a new search interval, either (a,b1) or (b2,a)

Example:

  • Pick 4 from A, searching close to (4,4)
  • A) Pick 2 from B, searching close to (2,4)
  • .... Pick 3 from C, it's in the interval. searching close to (2,4)
  • .... Pick 7 from D, interval is (2,7), distance is 5.
  • B) Pick 6 from B, searching close to (4,6)
  • ....


来源:https://stackoverflow.com/questions/12124045/what-type-of-algorithm-should-i-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!