题目描述:
有两个数组a,b,大小都为n,数组元素的值任意整型数,无序;
要求:通过交换a,b中的元素,使数组a元素的和与数组b元素的和之间的差最小。
#include "stdafx.h" #include <math.h> #include <time.h> #include <stdlib.h> void print_arr(int a[], int b[], int n) { printf("a: "); for (int i=0;i<n;i++) { printf("%d ", a[i]); } printf("\n"); printf("b: "); for (int i=0;i<n;i++) { printf("%d ", b[i]); } printf("\n"); printf("\n"); } bool swap_min(int a[], int b[], int n) { printf("before swap:\n"); print_arr(a, b, n); // 初始化差值 int sum_a=0; int sum_b=0; for (int k=0;k<n;k++) { sum_a += a[k]; sum_b += b[k]; } int delta_init = abs(sum_a - sum_b); for (int i=0;i<n;i++) { /*if (delta_init == 0) // 优化处理 { break; }*/ int sum_a=0; int sum_b=0; for (int k=0;k<n;k++) { sum_a += a[k]; sum_b += b[k]; } // 假设交换,差值是否更小 bool bswp = false; int jpos = 0; for (int j=0;j<n;j++) { int sum_atemp = sum_a-a[i]+b[j]; int sum_btemp = sum_b-b[j]+a[i]; int delta_temp = abs(sum_atemp-sum_btemp); if (delta_temp < delta_init) { delta_init = delta_temp; jpos = j; bswp =true; } } // 假设成功,执行交换元素 if (bswp) { int tmp = a[i]; a[i] = b[jpos]; b[jpos] = tmp; } } printf("after swap:\n"); print_arr(a,b,n); return true; } int _tmain(int argc, _TCHAR* argv[]) { int a[5] = {0, 0, 0, 0, 9};//1,2,3,4,5 int b[5] = {1, 2, 5, 4, 3};//6,7,8,9,100 int c[] = {1,2,3,4,5}; int d[] = {6,7,8,9,100}; int e[]={1,2,3,4,5}; int f[]={10,20,30,40,50}; //////////////////////// swap_min(a, b, 5); swap_min(c, d, 5); swap_min(e, f, 5); errno_t err; unsigned int number; err = rand_s(&number); int m[100]; int n[100]; srand( (unsigned)time(NULL)); //生成种子 for (int i=0;i<100;i++) { m[i]=rand()%100; n[i]=abs(rand()%200-100); } swap_min(m, n, 10); //////////////////////// getchar(); return 0; }