繁体   English   中英

我的算法中的缺陷在哪里找出是否存在两个数组A,B的排列,使得它们具有(A [i] + B [i])> = k

[英]Where is the flaw in my algorithm to find whether there exists a permutation of two arrays A,B such that they have (A[i]+B[i]) >= k

例如,用

k=10
A=[2,1,3]
B=[7,8,9]

答案是肯定的,因为你可以重新确定要素

A=[1,2,3]
B=[9,8,7]

那么对于i=0,1,2A[i]+B[i] >= 10 = k是正确的。 我的算法很贪婪,就像

int k = parameters[1];
int[] A = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int?[] B = Array.ConvertAll(Console.ReadLine().Split(' '), Extensions.ToNullableInt);

Array.Sort(B);
for(int j = 0; j < A.Length; ++j)
{
    bool found = false;
    for(int m = 0; j < B.Length && !found; ++j)
    {
        if(B[m] == null)
            continue;
        if((A[j] + B[m]) >= k)
        {
            found = true;
            B[m] = null;
        }
    }
    if(!found)
    {
        Console.WriteLine("NO");
        return;
    }
}
Console.WriteLine("YES");

我想不出它会失败的任何情况。

排序A按降序排序B (证明这是您可以实现的最佳可能性)并检查:

  int[] A = new int[] { 2, 1, 3 };
  int[] B = new int[] { 7, 8, 9 };

  int maxK = A
    .OrderBy(x => x)
    .Zip(B.OrderByDescending(x => x), (a, b) => a + b)
    .Min();

并且你将得到maxK == 10因此你可以找到所有k <= maxK == 10的排列;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM