最近在网上偶然看到此题:
有两个序列a,b,大小都为n,序列元素的值任意整形数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小
经过一番思索,我试着用穷举法来解一下这道题,大概思路如下:
1、分别求a,b序列元素之和sum_a、sum_b
2、算出min = abs(sum_a - sum_b)
3、进行n*n遍历:交换a,b中的任意元素;每次交换都算出交换后sum(a)-sum(b)的绝对值,作为二维序列t的元素。
其中sum(a)-sum(b) = sum_a - a[i] +b[j] - ( sum_b + a[i] -b[j] ) = sum_a -sum_b +2*( b[j] -a[i] )
4、另min_t = t[0][0],接着遍历t序列:若min_t > t的元素,则用t的元素作为新的min_t值
5、判断min和min_t的大小:若min_t < min ,则a,b做元素交换;反之,则不用。
最终输出的即是满足要求的序列。
代码如下:
#******穷举法******Python3.5****** import random def random_int_list(start,stop,length): #产生随机序列 start,stop = (int(start),int(stop)) if start <= stop else (int(stop),int(start)) length = int(abs(length)) if length else 0 random_list = [] for i in range(length): random_list.append(random.randint(start,stop)) return random_list a = random_int_list(1,100,5) b = random_int_list(1,100,5) t = [[0 for i in range(5)] for i in range(5)] #初始化二维序列t print('a = ',a,'b = ',b,'t = ',t) sum_a = sum(a) sum_b = sum(b) min = abs(sum_a - sum_b) print('sum_a = ',sum_a,'sum_b = ',sum_b,'min = ',min) print('===============================================') for i in range(5): for j in range(5): t[i][j] = abs(sum_a -sum_b + 2*(b[j] - a[i])) print('t = ',t) print('===============================================') min_t = t[0][0] for i in range(5): for j in range(5): if( min_t > t[i][j]): min_t = t[i][j] temp1= i temp2 = j if min > min_t: temp = a[temp1] a[temp1] = b[temp2] b[temp2] = temp print('a = ',a,'b = ',b)