划分数组
将数组划分成两个子数组,使得两个子数组的差值(绝对值)最小,求这个差值
例子:
输入:
6
32 34 2 7 10 43
输出:
4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp_int(const void *e1, const void *e2) {
return *((int *)e1) - *((int *)e2);
}
int main() {
int n = 0;
scanf("%d\n", &n);
int *a;
a = new int[n];
memset(a, 0, sizeof(int)*n);
for (int i=0; i<n; ++i) {
scanf("%d", &a[i]);
}
qsort(a, n, sizeof(int), cmp_int);
int sum1 = 0;
int sum2 = 0;
for (int i=0; i<n; ++i)
sum1 += a[i];
int k=-1;
int d = 0;
int min_d = abs(sum1-sum2);
do {
k = -1;
for (int i=0; i<n; ++i) {
d = abs(sum1 - sum2 - a[i] - a[i]);
if (d < min_d) {
min_d = d;
k = i;
}
}
if (k != -1) {
sum1 -= a[k];
sum2 += a[k];
a[k] = 0;
}
} while (k!=-1);
delete [] a;
printf("%d\n", min_d);
}
此题可以使用分治法,但是我不想写出这个代码,以后自己在补充!!!