1.随机选择
sort_algorithm 最快的算法就是
但如果直接要寻找,那最快的算法可以是
selection algorithm:
random_selection(array,i)伪代码:
if len(array) = 1
return array[1]
else:
select a pivot
sort the pivot to the right place j
if (j=i) return j
if (j>i) return random_selection(array[:j],i)
else return random_selection(array[j+1:],j-i)
random select one pivot
最坏的情况:
平均(一般)复杂度:
代码实现(python):
import random
def random_selection(A,i):
length = len(A)
if(len(A) == 1):
return A[0]
else:
##随机选择一个pivot
P = random.randint(0,len(A)-1)
#print(P)
##把P排到正确的地方
(A,j) = partition(A,P)
A[0], A[j-1] = A[j-1],A[0]
#print(A)
if(j == i):
return A[j - 1]
elif (j > i):
return random_selection(A[:j-1],i)
else:
return random_selection(A[j:],i-j)
def partition(A,P):
A[0], A[P] = A[P], A[0]
i = 1
for j in range(1,len(A)):
if (A[j] <= A[0]):
A[i],A[j] = A[j], A[i]
i += 1
return (A,i)
2. short cut porblem(最小路径问题)
adjacency list
adjacency mateix
contraction algorithm:(伪代码)
if remianing two nodes:
- return count
else:
-
random selection( pick a remaining edge(u,v) uniformly at random
-
merge u and v into a single vertax
-
self-loop
不是每次都能得出最小路径,能得到最小路径的成功率
挑选任意最小路径(A,B)的概率是:
如果做 次
其中有最小路径的概率 是
如果做 次
其中有最小路径的概率是:
算法的时间复杂度:
short_cut 算法代码:
import random
#读入一个文件,各行形成节点的字典
def buildgragh(filename):
graph = {}
with open(filename) as f:
for l in f.readlines():
nodelist = l.split()
graph[nodelist[0]] = nodelist[1:]
return graph
#找到graph中的最小cut
def findmincut(graph):
#如果graph的长度《=2,返回graph
if(len(graph) <= 2):
final_graph = graph
return final_graph
else:
#建立一个edge库
edge = []
for k in graph.keys():
for i in graph[k]:
edge.append((k,i))
#随机选择一条边作为merge 边
select_edge = random.choice(edge)
v = select_edge[0]
v_to_merge = select_edge[1]
#把两条边合并起来
final_edges_v = []
for i in (graph[v]+graph[v_to_merge]):
if (i!= v) and (i != v_to_merge):
final_edges_v.append(i)
#更新node_v
graph[v] = final_edges_v
#删除掉v_to_merge节点
del graph[v_to_merge]
#更新其他节点
for k in graph.keys():
tem_list = graph[k].copy()
# print(range(len(graph[k])))
for i in range(len(graph[k])):
if(graph[k][i] == v_to_merge):
tem_list[i] = v
# elif (graph[k][i] == v_to_merge and v in graph[k]):
# del tem_list[i]
graph[k] = tem_list
return findmincut(graph)
graph = buildgragh("MinCut.txt")
m = len(graph)
final_mincut = m*(m-1)/2
for i in range(100):
graph1 = graph.copy()
final_graph = findmincut(graph1)
element = list(final_graph.keys())[0]
mincut = len(final_graph[element])
if (final_mincut > mincut):
final_mincut = mincut
print(final_mincut)