Exemple #1
0
#coding: latin1

#< full
from algoritmia.problems.tsp import TspAsBranchAndBoundProblem
from algoritmia.schemes.branchandbound import BranchAndBoundSolver
from algoritmia.datastructures.prioritydicts import MinHeapMap
from algoritmia.datastructures.graphs import UndirectedGraph, WeightingFunction

w = WeightingFunction({(0,1): 0, (0,2): 15, (0,3): 2, (1,3): 3, (1,4): 13, (2,3): 11,
                       (2,5): 4, (3,4): 5, (3,5): 8, (3,6): 12, (4,7): 9, (5,6): 16,
                       (5,8):10, (6,7): 17, (6,8): 1, (6,9): 6, (7,9): 14, (8,9): 7},
                       symmetrical=True)
G = UndirectedGraph(E=w.keys())
problem = TspAsBranchAndBoundProblem(G, w)
solver = BranchAndBoundSolver(problem, lambda keyvalues: MinHeapMap(keyvalues))
x, weight = solver.solve()
print('Camino', x, 'con peso', weight)
#> full
#coding: latin1

#< full
from algoritmia.problems.randomwalk import RandomWalkAsBranchAndBoundProblem
from algoritmia.schemes.branchandbound import BranchAndBoundSolver
from algoritmia.datastructures.prioritydicts import MaxHeapMap
from random import seed, randrange
from algoritmia.utils import argmax

seed(0)
walk = [0]
for i in range(999): walk.append(walk[-1] + (1 if randrange(2) else -1))
problem = RandomWalkAsBranchAndBoundProblem(walk)
s, minval = BranchAndBoundSolver(problem, lambda keyvalues: MaxHeapMap(keyvalues)).solve()
print("Por ramificación y acotación. Índice:", s.i, "Valor:", minval)
print("Por fuerza bruta.             Índice:", end= ' ')
print(argmax(range(len(walk)), lambda i: walk[i]), "Valor:", max(walk)) 
#> full
#coding: latin1

#< full
from algoritmia.problems.matching import MatchingAsBranchAndBoundProblem3
from algoritmia.schemes.branchandbound import BranchAndBoundSolver
from algoritmia.datastructures.prioritydicts import MinHeapMap

c = [[3, 1, 2, 1], [3, 3, 4, 2], [2, 1, 1, 1], [4, 2, 4, 3]]
problem = MatchingAsBranchAndBoundProblem3(c)
x, cost = BranchAndBoundSolver(
    problem, lambda keyvalues: MinHeapMap(keyvalues)).solve()
print('Las piezas se ensamblan en el orden', x, 'con coste', cost)
#> full
Exemple #4
0
#coding: latin1

#< full
from algoritmia.problems.knapsack import KnapsackAsBranchAndBoundProblem
from algoritmia.schemes.branchandbound import BranchAndBoundSolver

v, w, W = [10, 2, 3, 4, 2], [12, 5, 6, 2, 6], 10
problem = KnapsackAsBranchAndBoundProblem(v, w, W)
solver = BranchAndBoundSolver(problem)
solution, profit = solver.solve()
print('Mejor solución:', solution, 'con beneficio', profit)
#> full