交换两数组中的元素使得这两个数组的差最小
a1=A-B
a2=(A-a[i]+b[j])-(B-b[j]=a[i])
=(A-B)-2*(a[i]-b[j])
=a1-2*(a[i]-b[j])
a[i]-b[j]~~(0,a1) min=a1/2;
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<string>
using namespace std;
void swap(float *A, int lenA, float *B, int lenB, float a1)
{
float min_ = 10000;
int k1 = -1;
int k2 = -1;
for (int i = 0; i < lenA;i++)
for (int j = 0; j < lenB; j++){
int sub = abs((A[i] - B[j])-a1*1.0/2);
if (sub < min_)
{
min_ = sub;
k1 = i;
k2 = j;
}
}
int temp = A[k1];
A[k1] = B[k2];
B[k2] = temp;
}
float FinSum(float A[], int lenA, float B[], int lenB)
{
float Subsum1 = 0;
float Subsum2 = 0;
for (int i = 0; i < lenA; i++)
{
Subsum1 += A[i];
}
for (int i = 0; i < lenA; i++)
{
Subsum2 += B[i];
}
float a1 = Subsum1 - Subsum2;
return a1;
}
int main()
{
float A[] = { 4,5,6 };
int len_a = 3;
float B[] = { 1,2,3};
int len_b = 3;
float a1 = 1000000;
float a2 = FinSum(A, len_a, B, len_b);
while (a2 < a1)
{
a1 = a2;
swap(A, len_a, B, len_b, a2);
a2 = FinSum(A, len_a, B, len_b);
}
return 0;
}