![](/img/trans.png)
[英]Where is the flaw in my algorithm to find all pairs in an array whose sum divides 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,2
, A[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.