- 论坛徽章:
- 0
|
我的程序没31楼那么好
但一样实现了算法
- #include <stdio.h>
- int main()
- {
- int a[20], b[20];
- int n, i, t;
- /* load data */
- do
- {
- printf("Set the size of array:");
- scanf("%d", &n);
- }while (n < 1 || n > 20);
- printf("arry a:");
- for(i = 0;i < n; i++)
- scanf("%d", a + i);
- printf("arry b:");
- for(i = 0;i < n; i++)
- scanf("%d", b + i);
- /* sort array a,b and let sum(a) < sum(b) */
- sort(a, n);
- sort(b, n);
- if (sum(a, n) > sum(b, n))
- { /* exchange a,b */
- for(i = 0;i < n;i++)
- {
- t = a[i];
- a[i] = b[i];
- b[i] = t;
- }
- }
- /* now sum(a) <= sum(b),if lower to make sum(a) near to sum(b) */
- if (sum(a, n) < sum(b, n))
- make_near(0 , n, a ,b);
- /* output the result */
- sort(a, n);
- puts("\nsum a:");
- for (i = 0;i < n;i++)
- if (i < n - 1)
- printf("%d+", a[i]);
- else
- printf("%d = ", a[i]);
- printf("%d\n", sum(a, n));
- puts("sum b:");
- for (i = 0;i < n;i++)
- if (i < n - 1)
- printf("%d+", b[i]);
- else
- printf("%d = ", b[i]);
- printf("%d\n", sum(b, n));
- printf("value between a and b is:%d\n", sum(b, n) - sum(a, n));
- return 0;
- }
- /* sort the array: small to big */
- void sort(int *arr, int n)
- {
- int i, j;
- for (i = n - 1;i > 0;i--)
- for(j = 1;j <= i ;j++)
- {
- if (arr[j - 1] > arr[j])
- exchange_p(arr + (j - 1), arr + j);
- }
- }
- int sum(int *arr, int n)
- {
- if (n == 1)
- return *arr;
- return *arr + sum(arr + 1, n - 1);
- }
- /* exchange tow pointer value */
- void exchange_p(int *a, int *b)
- {
- int t;
- t = *a - *b;
- *b += t;
- *a -= t;
- }
- /* exchange the elements of array a and b,
- to make sum(a) nearest to sum(b),
- and make sure sum(b) always greater than sum(a),
- if not,should exchange the elements back.
- the condition of return: sum(a) == sum(b) or m point to the end of a
- */
- void make_near(int m, int n, int *a, int *b)
- {/* m point to the current element of a, n is the array's size */
- int i;
- for (i = n - 1;i >= 0;i--)
- {
- if (a[m] < b[i])
- {
- exchange_p(a + m, b + i);
- /* success to exchange and go to next step */
- if (sum(a, n) < sum (b, n))
- break;
- /* sum(a) == sum(b) ,return */
- else if (sum(a, n) == sum(b ,n))
- return;
- /* failure to exchange,exchange back */
- else
- exchange_p(a + m, b + i);
- }
- else/* it's no need to process a[m] >= b[i],go to next step */
- break;
- }
- sort(b ,n);
- /* m point to the end of a*/
- if (m == n)
- return;
- /* m move to the next element */
- make_near(m + 1, n, a, b);
- }
复制代码
[ 本帖最后由 UCfree 于 2007-12-13 17:00 编辑 ] |
|