Exemplo n.º 1
0
# constraint : leave each city coming from another city
for i in N:
    model += xsum(x[a] for a in IN[i]) == 1

# no subtours of size 2
for a in A:
    if (a[1], a[0]) in A.keys():
        model += x[a] + x[a[1], a[0]] <= 1

# computing farthest point for each point
F = []
G = nx.DiGraph()
for ((i, j), d) in A.items():
    G.add_edge(i, j, weight=d)
for i in N:
    P, D = nx.dijkstra_predecessor_and_distance(G, source=i)
    DS = list(D.items())
    DS.sort(key=lambda x: x[1])
    F.append((i, DS[-1][0]))

model.lazy_constrs_generator = SubTourCutGenerator(F)
model.optimize()

print(model.status)

print('best route found has length {}'.format(model.objective_value))

arcs = [a for a in A.keys() if x[a].x >= 0.99]
print('optimal route : {}'.format(arcs))
Exemplo n.º 2
0
                       for j in range(n) if i + j == k) <= 1
            if cut.violation > 0.001:
                model.add_cut(cut)


# number of queens
n = 50

queens = Model('queens', MAXIMIZE)

x = [[
    queens.add_var('x({},{})'.format(i, j), var_type=BINARY) for j in range(n)
] for i in range(n)]

# one per row
for i in range(n):
    queens += xsum(x[i][j] for j in range(n)) == 1, 'row({})'.format(i)

# one per column
for j in range(n):
    queens += xsum(x[i][j] for i in range(n)) == 1, 'col({})'.format(j)

queens.lazy_constrs_generator = DiagonalCutGenerator()
queens.optimize()

stdout.write('\n')
for i, v in enumerate(queens.vars):
    stdout.write('O ' if v.x >= 0.99 else '. ')
    if i % n == n - 1:
        stdout.write('\n')