标签:style blog color os io strong ar for div
代码实现:
1 // 32.cc 2 #include <iostream> 3 using namespace std; 4 5 // 计算数组的和 6 int sum(const int* a, int n) { 7 int count = 0; 8 for (int i = 0; i < n; i++) 9 count += a[i]; 10 return count; 11 } 12 13 // 交换数组元素得到平衡集 14 void balance_swap(int* a, int* b, int n) { 15 // a指向和比较大的集合 16 if (sum(a, n) < sum(b, n)) { 17 int* t = a; 18 a = b; 19 b = t; 20 } 21 22 bool loop = true; 23 while (loop) { 24 loop = false; 25 for (int i = 0; i < n; i++) { 26 for (int j = 0; j < n; j++) { 27 int diff = a[i] - b[j]; 28 int A = sum(a, n) - sum(b, n); 29 if (diff > 0 && diff < A / 2) { 30 loop = true; 31 int tmp = a[i]; 32 a[i] = b[j]; 33 b[j] = tmp; 34 } 35 } 36 } 37 } 38 } 39 40 // 打印数组元素 41 void print(const int* a, int n) { 42 for (int i = 0; i < n; i++) 43 cout << a[i] << " "; 44 cout << endl; 45 } 46 47 int main() { 48 int a[] = {80, 40, 60, 10, 20, 30}; 49 int b[] = {10, 20, 50, 40, 30, 20}; 50 int n = sizeof(a) / sizeof(int); 51 52 balance_swap(a, b, n); 53 54 print(a, n); 55 print(b, n); 56 57 return 0; 58 }
输出:
$ ./a.exe 50 40 60 10 20 30 10 20 80 40 30 20
标签:style blog color os io strong ar for div
原文地址:http://www.cnblogs.com/dracohan/p/3949099.html