给定两个无序正整数列表,最大化 A[i]*B[i] + A[i]*B[j] + A[j]*B[j],其中i != j。

4

你能帮我解决这个算法问题吗:

给定两个长度相等的整数数组 a[]b[],元素值大于等于1。

找到不相等的下标 iji != j),使得值 -

max(a[i]*b[i] + a[i] * b[j] + a[j] * b[j], a[i]*b[i] + a[j] * b[i] + a[j] * b[j])

最大。

示例:

a = [1, 9, 6, 6]b = [9, 1, 6, 6]

当 i = 2,j=3 时(从0开始表示下标)最大值为: a[2]*b[2] + a[2]*b[3] + a[3] * b[3] = 6*6+6*6+6*6 = 108

有没有一种方法可以在小于二次时间复杂度的情况下找到 i 和 j? 同样的问题也适用于在小于二次时间复杂度的情况下找到目标函数的值?

谢谢!


你提到了 i != j,但在方程式中你使用了 a[i] * b[i],在这种情况下,a 和 b 具有相同的索引。 - Hamzah
@DataMoguls 是的。我们从a和b中在索引i处取1对值,然后在索引j处取另外1对值。您能否澄清您困惑的是什么? - Sergey
2
这些数组只包含正数吗? - MrSmith42
@MrSmith42 是的,只能为正整数。将添加到描述中。 - Sergey
@学习数学。例如:a=[1, 9, 6, 6]和b=[9, 1, 6, 6]。 你建议将i=0和j=1,这样我们将有max(9+9+81, 9+9+1)=99,但最大值应该是i=2和j=3,max(66 + 66 + 66, 66 + 66 + 66) = 108。 - Sergey
2个回答

4
这是我尝试实现David Eisenstat的想法。我认为i != j的限制使得这更加复杂,但无论如何,我欢迎改进代码的建议。在最后进行了一项针对暴力方法的测试。
对于线条A[i]*x + A[i]*B[i]的上凸壳构建依赖于将从线条转换而来的对偶点应用于Andrew的单调链凸包算法。
Python代码:
# Upper envelope of lines in the plane

from fractions import Fraction
import collections

def get_dual_point(line):
  return (line[0], -line[1])

def get_primal_point(dual_line):
  return (dual_line[0], -dual_line[1])

def get_line_from_two_points(p1, p2):
  if p1[0] == p2[0]:
    return (float('inf'), 0)

  m = Fraction(p1[1] - p2[1], p1[0] - p2[0])
  b = -m * p1[0] + p1[1]

  return (m, b)

def cross_product(o, a, b):
  return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


# lower_hull has the structure [(dual_point, original_line, leftmost_x, index)]
def get_segment_idx(lower_hull, x):
  lo = 0
  hi = len(lower_hull) - 1

  # Find the index of the first
  # x coordinate greater than x
  while lo < hi:
    mid = lo + (hi - lo + 1) // 2

    if lower_hull[mid][2] <= x:
      lo = mid
    else:
      hi = mid - 1

  return lo


# Assumes we add points in order of increasing x-coordinates
def add_right_to_lower_hull(lower_hull, point):
  while len(lower_hull) > 0 and lower_hull[-1][0][0] == point[0][0] and lower_hull[-1][0][1] > point[0][1]:
    lower_hull.pop()
  while len(lower_hull) > 1 and cross_product(lower_hull[-2][0], lower_hull[-1][0], point[0]) <= 0:
    lower_hull.pop()
  if not lower_hull or lower_hull[-1][0][0] != point[0][0]:
    lower_hull.append(point)
  # Each segment of the lower hull
  # in the dual plane is a line intersection
  # in the primal plane.
  if len(lower_hull) == 1:
    lower_hull[0][2] = -float('inf')
  else:
    line = get_line_from_two_points(lower_hull[-1][0], lower_hull[-2][0])
    lower_hull[-1][2] = get_primal_point(line)[0]

  return lower_hull


# Assumes we add points in order of decreasing x-coordinates
def add_left_to_lower_hull(lower_hull, point):
  while len(lower_hull) > 0 and lower_hull[0][0][0] == point[0][0] and lower_hull[0][0][1] > point[0][1]:
    lower_hull.popleft()
  while len(lower_hull) > 1 and cross_product(lower_hull[1][0], lower_hull[0][0], point[0]) >= 0:
    lower_hull.popleft()
  if not lower_hull or lower_hull[0][0][0] != point[0][0]:
    lower_hull.appendleft(point)
  # Each segment of the lower hull
  # in the dual plane is a line intersection
  # in the primal plane.
  if len(lower_hull) == 1:
    lower_hull[0][2] = -float('inf')
  else:
    line = get_line_from_two_points(lower_hull[0][0], lower_hull[1][0])
    lower_hull[1][2] = get_primal_point(line)[0]

  return lower_hull


# Maximise A[i] * B[i] + A[i] * B[j] + A[j] * B[j]
def f(A, B):
  debug = False

  if debug:
    print("A: %s" % A)
    print("B: %s" % B)

  best = -float('inf')
  best_idxs = ()

  indexed_lines = [((A[i], A[i] * B[i]), i) for i in range(len(A))]

  # Convert to points in the dual plane
  # [dual_point, original_line, leftmost x coordinate added later, original index]
  dual_points = [[get_dual_point(line), line, None, i] for line, i in indexed_lines]

  # Sort points by x coordinate ascending
  sorted_points = sorted(dual_points, key=lambda x: x[0][0])

  if debug:
    print("sorted points")
    print(sorted_points)

  # Build lower hull, left to right
  lower_hull = []

  add_right_to_lower_hull(lower_hull, sorted_points[0])

  for i in range (1, len(sorted_points)):
    # Query the point before inserting it
    # because of the stipulation that i != j
    idx = sorted_points[i][3]
    segment_idx = get_segment_idx(lower_hull, B[idx])
    m, b = lower_hull[segment_idx][1]
    j = lower_hull[segment_idx][3]
    candidate = m * B[idx] + b + A[idx] * B[idx]

    if debug:
      print("segment: %s, idx: %s, B[idx]: %s" % (segment_idx, idx, B[idx]))

    if candidate > best:
      best = candidate
      best_idxs = (idx, j)

    add_right_to_lower_hull(lower_hull, sorted_points[i])
  
  if debug:
    print("lower hull")
    print(lower_hull)

  # Build lower hull, right to left
  lower_hull = collections.deque()

  lower_hull.append(sorted_points[len(sorted_points) - 1])

  for i in range (len(sorted_points) - 2, -1, -1):
    # Query the point before inserting it
    # because of the stipulation that i != j
    idx = sorted_points[i][3]
    segment_idx = get_segment_idx(lower_hull, B[idx])
    m, b = lower_hull[segment_idx][1]
    j = lower_hull[segment_idx][3]
    candidate = m * B[idx] + b + A[idx] * B[idx]

    if debug:
      print("segment: %s, idx: %s, B[idx]: %s" % (segment_idx, idx, B[idx]))

    if candidate > best:
      best = candidate
      best_idxs = (idx, j)

    add_left_to_lower_hull(lower_hull, sorted_points[i])

  if debug:
    print("lower hull")
    print(lower_hull)

  return best, best_idxs


#A = [1, 9, 6, 6]
#B = [9, 1, 6, 6]

#print("")
#print(f(A, B))


# Test

import random

def brute_force(A, B):
  best = -float('inf')
  best_idxs = ()

  for i in range(len(A)):
    for j in range(len(B)):
      if i != j:
        candidate = A[i] * B[i] + A[i] * B[j] + A[j] * B[j]
        if candidate > best:
          best = candidate
          best_idxs = (i, j)

  return best, best_idxs


num_tests = 500
n = 20
m = 1000

for _ in range(num_tests):
  A = [random.randint(1, m) for i in range(n)]
  B = [random.randint(1, m) for i in range(n)]

  _f = f(A, B)
  _brute = brute_force(A, B)

  if _f[0] != _brute[0]:
    print("Mismatch")
    print(A)
    print(B)
    print(_f, _brute)

print("Done testing.")

看起来,我不理解如何将用于线交点任务的凸包转换为用于点的凸包。您使用了对偶平面,但我对此一无所知。谢谢,我需要一些时间来理解。 - Sergey
1
@Sergey,我在阅读一些文本时看到了这个转换。我现在找不到它了,但当时我正在谷歌上搜索线的凸包、增量式凸包、上凸壳,我不记得确切的搜索词了。这里有另一篇文章可能会有所帮助:https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.212.370&rep=rep1&type=pdf - גלעד ברקן

3

是的,有一个O(n log n)时间复杂度的算法。

如果我们看一下函数f(x) = max {a[i] b[i] + a[i] x | i}, 它会形成一个下凸壳。基本上,只需要计算每个j的 f(b[j]) + a[j] b[j] ,但需要注意i ≠ j。

为了解决这个问题,我们采用增量外壳算法, 每次插入的时间复杂度为摊还的O(log n)。典型算法按排序顺序保持外壳, 允许O(log n)时间复杂度的查询。从空壳开始,对每个索引i进行查询和插入。 正序和逆序各执行一次,然后取最大值。


不确定如何以O(log n)的时间查询?为了评估max{...},我们需要进行O(n)次计算,并对每个i都这样做。我是正确的吗?我不知道我们如何改进它。 - Sergey
@Sergey,实现增量凸壳的最简单方法是对a和b应用相同的随机排列,并在不平衡的二叉搜索树中维护当前凸壳边缘,由于洗牌,期望会平衡。搜索树从左到右排序,因此查询基本上是常规BST查找。更多细节请参考计算几何文本。 - David Eisenstat
@David_Eisenstat,抱歉,我明白我们如何应用凸包算法,但我不明白为什么它会是(n log n)。我的推理如下: 1)凸包的速度是O(k log(k)),其中k是点的数量。 2)在任务的情况下,点的总数:k = O(n^2)在最坏的情况下,这相当于线段交点的数量(更准确地说,最坏情况下约为n *(n-1)/ 2)因此:在最坏的情况下是O(n^2 log(n))。我有什么遗漏吗? - Sergey
1
@Sergey 每个 a[i] b[i] + a[i] x 都是平面上的一条直线。如果我们在坐标轴上画几条随机的直线,很容易看出每个 x 的最佳选择是当前顶部的那条直线。这意味着我们想要跟踪的直线段形成了一个凸包。我们希望将形成凸包的相关线段排列好,以便我们可以高效地查询 x 作为 b[j] - גלעד ברקן
添加了Python代码来尝试实现这个功能。根据最后的暴力测试,它似乎可以工作。i != j 使得它有点难以实现和调试。 - גלעד ברקן

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接