# 确定集合中是否存在两个其和刚好为X的元素？

《算法导论》第三版 P22，2.3-7练习题

list1 = [1,2,3,4,5,6,7,8,10,19];
count = len(list1);
stack4 = []
stack2 = []

def bsf2(list0, start1, end1, start2, end2, a):
flags = [False, False, False, False];

if len(stack4) > 0:
return True

if start1 == end1 and start2 == end2:
if a == list0[start1] + list0[end2]:
stack4.append(end2)
stack4.append(end2)
stack4.append(start1)
stack4.append(start1)
return True
return False

if list0[start1] + list0[start2] > a or list0[end1] + list0[end2] < a:
return False

mid1 = (int)((start1 + end1) /2);
mid2 = (int)((start2 + end2) /2);
flags[0] = bsf2(list0, start1, mid1, start2, mid2, a);
flags[1] = bsf2(list0, start1, mid1, mid2 + 1, end2, a);
flags[2] = bsf2(list0, mid1 + 1, end1, start2, mid2, a);
flags[3] = bsf2(list0, mid1 + 1, end1, mid2 + 1, end2, a);

if flags[0] and flags[1] and flags[2] and flags[3]:
stack4.append(end2)
stack4.append(start2)
stack4.append(end1)
stack4.append(start1)
return True

if flags[0] and flags[1] and flags[2]:
return bsf2(list0, start1, end1, start2, mid2, a)

if flags[0] and flags[1] and flags[3]:
return bsf2(list0, start1, end1, mid2 + 1, end2, a)

if flags[0] and flags[2] and flags[3]:
return bsf2(list0, start1, mid1, start2, end2, a)

if flags[1] and flags[2] and flags[3]:
return bsf2(list0, mid1 + 1, end1, start2, end2, a)

if flags[0] and flags[2]:
return bsf2(list0, start1, mid1, start2, mid2, a)

if flags[0] and flags[3]:
return bsf2(list0, start1, mid1, mid2 + 1, end2, a)

if flags[1] and flags[2]:
return bsf2(list0, mid1 + 1, end1, start2, mid2, a)

if flags[1] and flags[3]:
return bsf2(list0, mid1 + 1, end1, mid2 + 1, end2, a)

def rbsf(list0, start, end, a):
if start == end:
return
if list0[start] + list0[start + 1] > a or list0[end] + list0[end - 1] < a:
return
stack2.append(end);
stack2.append(start);

mid = (int)((start + end) / 2);
rbsf(list0, start, mid, a);
rbsf(list0, mid + 1, end, a);

return;

rbsf(list1, 0, count - 1, 9);
stack2.reverse();
if len(stack2) > 0:
print(stack2);
else:
print("find no section")

while(len(stack2) > 0):
print(stack2[0:2])
start = stack2.pop(0)
end = stack2.pop(0)
mid = (int)((start + end) / 2);
flag = bsf2(list1, start, mid, mid + 1, end, 9)
if flag:
print(stack4)
break
else:
print("Not found")

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120