Professional Documents
Culture Documents
AB Algoritmia =
Algoritmia = tratamiento sistemático de
técnicas fundamentales para
el diseño y análisis de
algoritmos eficientes
G. Brassard y P. Bratley
Fundamentos de Algoritmia (Prólogo)
¿qué herramientas?:
Σ bixi
(x1,x2,x3) 1≤i≤3
(i) (1,1/6,0) 46
(ii) (0,3/4,1) 49
(iii) (0,1,5/8) 49’75
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 11
El problema de la mochila
• Solución voraz:
– El conjunto de candidatos son los objetos, tomándose de ellos
cierta fracción.
– Un conjunto de candidatos es completable si la suma de sus
pesos no supera la capacidad de la mochila, y es una solución
si iguala dicha capacidad.
Σ bixi.
– La función objetivo a maximizar es 1≤i≤n
{Pre:∀i∈1..n:peso[i]>0 ∧
∀i∈1..n-1:benef[i]/peso[i]≥benef[i+1]/peso[i+1]}
función mochila(benef,peso:vectReal; cap:real) devuelve vectReal
variables resto:real; i:entero; sol:vectReal
principio
para todo i en 1..n hacer
sol[i]:=0.0 {inicializar solución}
fpara;
resto:=cap; {capacidad restante}
i:=1;
mq (i≤n) and (peso[i]≤resto) hacer
sol[i]:=1; resto:=resto-peso[i]; i:=i+1
fmq;
si i≤n entonces sol[i]:=resto/peso[i] fsi;
devuelve sol
fin
{Post: sol es solución óptima del problema de la mochila}
12 3 3 12
3 3
5 5
1 2 5 1 2 5
21 4 21 4
4 4
• Búsqueda de caminos de longitud mínima
– longitud o coste de un camino: suma de los pesos de las aristas que lo componen
– cálculo de la longitud mínima de los caminos existentes entre dos vértices dados
• Características del tipo de dato de las etiquetas (o pesos):
– dominio ordenado (<, =, ≤)
– operación suma (+):
• conmutativa
• con elemento neutro (0), que es además el peso más pequeño posible
• con elemento idempotente (∞), que es además el peso más grande posible
1
falso verdad falso
2 nil
2 1
2 1 nil
3
2 nil
3
3 1 2 nil nil
1
2 2 1 nil 2 3 nil nil
Grafo dirigido
3 nil
Listas de adyacencia
1 4 2 4 3 4
• Utilidad:
el grafo representa una distribución geográfica, donde las
aristas dan el coste (precio, distancia...) de la conexión entre
dos lugares y se desea averiguar el camino más corto
(barato...) para llegar a un punto partiendo de otro
E.W. Dijkstra:
“A note on two problems in connexion with
graphs”,
Numerical Mathematica, 1, pp. 269-271, 1959.
...
{se marca w como vértice tratado}
T:=T-{w};
{se recalculan las nuevas dist. mínimas}
para todo u en T hacer
si D[w]+etiqueta(g,w,u)<D[u]
ent D[u]:=D[w]+etiqueta(g,w,u)
fsi
fpara
frepetir;
devuelve D
fin
{Post: D=caminosMínimos(g,v)
Nota: el bucle principal se ejecuta n-2 veces porque el último camino queda
calculado después del último paso (no quedan vértices para hallar atajos)
Solución: nuevo tipo de cola con prioridades que permita el acceso directo
a cualquier elemento.
asegurar que todos los computadores pueden comunicar entre sí, minimizando el
precio total de la red
R.C. Prim:
“Shortest connection networks and some generalizations”,
Bell System Technical Journal, 36, pp. 1389-1401, 1957.
Coste: Θ(na)
(es decir, Θ(n3) si el grafo es denso)
si v∈U: arisMín[v]=<v,∞>
...
{a continuación se añade a la solución}
añade(gsol,mín,arisMín[mín].v,arisMín[mín].et);
{se añade mín al conjunto de vértices tratados}
arisMín[mín]:=<mín,∞>;
{se reorganiza el vector comprobando si la arista mínima de los
vértices todavía no tratados los conecta a mín}
para todo <v,x> en adyacentes(g,mín) hacer
si (arisMín[v].v≠v)and(x<arisMín[v].et)
entonces arisMín[v]:=<mín,x>
fsi
fpara
frepetir;
devuelve gsol
fin
{Post: gsol∈arm(g)}
• Algoritmo de Kruskal:
– Se basa también en la propiedad de los árboles de
recubrimiento de coste mínimo:
30 3
A B A B
40 40 4
50 C 60 C
10 20 1 2
D 50
E D E
→ {[A,B],[C,D,E]} → {[A,B,C,D,E]}
...
mq numClases(C)>1 hacer
{obtener y elim. la arista mín.de la cola}
<u,v,x>:=primero(T); borra(T);
{si la arista no provoca ciclo se añade a la
solución y se fusionan las clases corresp.}
ucomp:=clase(C,u); vcomp:=clase(C,v);
si ucomp≠vcomp entonces
fusiona(C,ucomp,vcomp);
añade(gsol,u,v,x)
fsi
fmq;
devuelve gsol
fin
{Post: gsol∈arm(g)}
• Subestructura óptima:
– Un problema posee una subestructura óptima si una solución óptima de
ese problema incluye soluciones óptimas de subproblemas.
a b c d e f
aparic. (en miles) 45 13 12 16 9 5
– Puede usarse un código de longitud fija (de 3 bits). El fichero requeriría 300.000 bits.
a b c d e f
cód.long.fija 000 001 010 011 100 101
a b c d e f
cód.long.var. 0 101 100 111 1101 1100
Este código ahorra algo más del 25% (requiere 224.000 bits en lugar de 300.000).
• Se precisa un código libre de prefijos:
– Ninguna codificación puede ser prefijo de otra.
– De esta forma, la decodificación es inmediata pues no hay ambigüedades.
– Por ejemplo: ‘001011101’ sólo puede ser ‘aabe’.
• El código se representa mediante un trie (árbol lexicográfico):
– árbol binario cuyas hojas son los caracteres codificados;
– el código de cada carácter es el camino desde la raíz hasta la hoja, donde ir al hijo
izquierdo significa ‘0’ e ir hacia el derecho significa ‘1’.
86 14 a:45 55
0 1 0 0 1
58 28 14 25 30
0 1 0 1 0 1 0 1 0 1
a:45 b:13 c:12 d:16 e:9 f:5 c:12 b:13 14 d:16
0 1
f:5 e:9
– Cada hoja está etiquetada con un carácter y su frecuencia.
– Cada nodo interno está etiquetado con la suma de los pesos de las hojas de
su subárbol.
– Un código óptimo siempre está representado por un árbol lleno: cada
nodo interno tiene dos hijos.
• Si el alfabeto que se quiere codificar es C, entonces el árbol del código
óptimo tiene |C| hojas y |C| – 1 nodos internos.
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 60
Códigos de Huffman
• El algoritmo voraz de Huffman construye el árbol A de
un código óptimo de abajo hacia arriba.
• Utiliza una cola Q de árboles con prioridades (las
frecuencias hacen de prioridades).
• Empieza con un conjunto de |C| hojas en Q y realiza
una secuencia de |C| – 1 “mezclas” hasta crear el árbol
final.
• En cada paso, se “mezclan” los dos objetos (árboles) de
Q que tienen menos frecuencia y el resultado es un
nuevo objeto (árbol) cuya frecuencia es la suma de las
frecuencias de los dos objetos mezclados.
f:5 e:9 c:12 b:13 d:16 a:45 c:12 b:13 14 d:16 a:45 (3º) 14 d:16 25 a:45
0 1 0 1 0 1
(1º) (2º) f:5 e:9 f:5 e:9 c:12 b:13
orden T
1 2 3: 5+ (5+10) + (5+10+3) = 38
1 3 2: 5+ (5+3) + (5+3+10) = 31
2 1 3: 10 + (10+5) + (10+5+3) = 43
2 3 1: 10 + (10+3) + (10+3+5) = 41
3 1 2: 3+ (3+5) + (3+5+10) = 29 óptimo
3 2 1: 3+ (3+10) + (3+10+5) = 34
k≠a,b
• Corrección:
Teorema 16.11 en [CLRS09, pp. 441-442]
(un par de páginas; sin gran dificultad).
1 2 5
1 2 5
1 2 5
• En términos matemáticos es el
problema del cálculo del hamiltoniano
de longitud mínima.
c (1,7) d (15,7)
e (15,4)
b (4,3)
a (0,0) f (18,0)
a
b 5
c 7,07 5
d 16,55 11,70 14
e 15,52 11,05 14,32 3
f 18 14,32 18,38 7,6 5
distan. a b c d e f
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 95
Heurísticas voraces: El problema del viajante de comercio
tA(n)≤cn2
– La solución de la ecuación
• Además:
La fusión de T[1..k] y T[k+1..n] (ya ordenados) en el mismo T[1..n] puede
hacerse en tiempo lineal utilizando sólo una cantidad fija de variables
auxiliares (independiente de n).
(Ejercicio 18 de la sección 5.2.4 de [Knu87] D.E. Knuth. El arte de programar
ordenadores. Volumen III: Clasificación y búsqueda. Editorial Reverté, 1987,
“nivel [40]” => “realmente difícil o largo”… ver artículo en “material adicional”.)
(nótese que la definición formal es más general: n puede ser par y además
puede haber elementos repetidos, incluida la mediana)
Primera solución:
– Ordenar T y extraer el elemento n/2-ésimo.
– Tiempo Θ(n log n).
{i ∈[1..n]| }
T[i ]< m < k , y
{i ∈[1..n]| T[i ]≤ m ≥ k }
Es decir, el elemento en posición k si T estuviese ordenado crecientemente.
– El producto es:
uv = 102s wy + 10s (wz+ xy) + xz
( ) ( )
t (n) = 3t n 2 + t n 2 + Θ (n)
Si n se supone potencia de 2,
( )
t (n) = 4t n 2 + Θ(n)
t (n) ∈O (n 2)
( ) ( ) ( )
t 2 (n) ∈t2 n 2 + t2 n 2 + t2 1+ n 2 + Θ(n)
Y por tanto,
( ) (
t 2 (n) ∈Θ nlog 3 ∈O n 1,59 )
– Debido a la constante multiplicativa, el algoritmo sólo es interesante en la
práctica para n grande.
– Una buena implementación no debe usar la base 10 sino la base más
grande posible que permita multiplicar dos “cifras” (de esa base)
directamente en hardware.
( );
2
En otras palabras, x 25 = x24x ; x24 = x12 etc
– Es claro que:
0 si n = 0
h(n) = 1+ h(n − 1) si n es impar
1+ h(n / 2) en otro caso
c
(∗∗) z, n, c…
a: a=cs
mod z
m: mensaje (ASCII)
Yo también…
(∗∗) ¿Por qué?
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 40
Introducción a la criptografía
• Cálculo de n:
egcd(n,φ,d,s,t);
si d=1
entonces s es el buscado
sino n no es ‘bueno’
fsi
ns+tφ=1⇒ns=1–tφ
n s mod φ = (1 – t φ) mod φ = 1 – 0 = 1
– Roberto calcula
cs mod z = (an mod z)s mod z = ans mod z = a
(porque ns mod φ = 1).
– Conoce z, n y c.
• Coste:
– Una suma de matrices n×n está en Θ(n2).
– Suponer que n es potencia de 2; se obtiene la recurrencia:
( )
T (n) = 7T n 2 + Θ(n2)
• ¿Y si n no es potencia de 2?
– Supongamos que está resuelto para n par.
– Si n es impar (mayor que 1), no bastan con n-1 días para la competición,
sino que se necesitan n.
Basta con resolver el problema resultante de añadir un participante
(ficticio) más: el n+1.
Como n+1 es par, podemos calcular el calendario, que consta de n días.
Una vez resuelto, si al participante i-ésimo le toca jugar el día j-ésimo
contra el participante n+1 (ficticio), eso significa que j es el día de
descanso para el participante i.
con xi ∈{0,1}, k ≤ i ≤ l
j
mochila 1, j , ∑ pi xi
i =1
j
mochila j + 1,n,C − ∑ pi xi
i=1
{
gj (c) = max gj + 1(c), g j+ 1(c − pj ) + bj }
dependiendo de que el objeto j-ésimo entre o no en la solución
(nótese que sólo puede entrar si c-pj≥0).
– Además,
gn+ 1 (c) = 0, para cualquier capacidad c
{
gj (c) = max gj − 1(c) , gj − 1(c − pj ) + bj }
dependiendo de que el objeto j-ésimo entre o no en la solución
(nótese que sólo puede entrar si c-pj≥0).
– Además,
g0(c ) = 0, para cualquier capacidad c
c=…
j=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
j=1
j=2
j=3
{
g j (c ) = max g j − 1(c) , g j − 1(c − p j ) + b j }
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 14
El problema de la mochila 0-1
algoritmo mochila(ent p,b:vect[1..n]de nat; ent Cap:nat;
sal g:vect[0..n,0..Cap]de nat)
variables c,j:nat
principio
para c:=0 hasta Cap hacer g[0,c]:=0 fpara;
para j:=1 hasta n hacer g[j,0]:=0 fpara;
para j:=1 hasta n hacer
para c:=1 hasta Cap hacer
si c<p[j] entonces
g[j,c]:=g[j-1,c]
sino
si g[j-1,c]≥g[j-1,c-p[j]]+b[j] entonces
g[j,c]:=g[j-1,c]
sino
g[j,c]:=g[j-1,c-p[j]]+b[j]
fsi
fsi
fpara
fpara
fin
2 5 6 4
12
4 9 9
V1 V2 V3 V4 V5
2 3
8
7 5
5 1 5 11
7 9
o 1 3 4 6 8 10 d
2 5 6 4
12
4 9 9
N max {N 3,i }
N 2,1 N 2,2 2,3 i= 0,1
N 1,3 N 2,2
v2,3 v3,3
N 2,0
N 2,1 N 3,0
N 1,4 N 2,4
v2,4 v3,4
N 2,0
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 22
Camino de coste mínimo en un grafo multietapa
• Solución de programación dinámica:
V1 V2 V3 V4 V5
2 3
8
7 5
5 1 5 11
7 9
o 1 3 4 6 8 10 d
2 5 6 4
12
4 9 9
C∗ (i , j ) = min
l ∈V i+ 1
{c( j ,l )+ C∗ (i + 1,l )}, para 1≤ i ≤ k − 2
( j ,l )∈A
V1 V2 V3 V4 V5
2 3
8
7 5
5 1 5 11
7 9
o 1 3 4 6 8 10 d
2 5 6 4
12
4 9 9
C∗ (i , j ) = min
l ∈V i+ 1
{c( j ,l )+ C∗ (i + 1,l )}, para 1≤ i ≤ k − 2
( j ,l )∈A
V1 V2 V3 V4 V5
2 3
8
7 5
5 1 5 11
7 9
o 1 3 4 6 8 10 d
2 5 6 4
12
4 9 9
C∗ (3,5)= min {8+ C ∗(4,7),11+ C ∗ (4,8),6+ C ∗(4,9)}= 13
C ∗ (3,6)= 4+ C ∗(4,8) = 13
C ∗ (2,2)= min {3+ C ∗(3,5),1+ C ∗ (3,6)}= 14
C ∗ (2,3)= 4+ C ∗(3,5) = 17
C ∗ (2,4)= min {5+ C ∗(3,5),9+ C ∗ (3,6)}= 18
C ∗ (1,1)= min {5+ C ∗(2,2),7+ C ∗ (2,3),2+ C ∗(2,4)}= 19
C∗ (i , j ) = min
l ∈V i− 1
{c(l , j )+ C∗ (i − 1,l )}, para 3≤ i ≤ k
(l , j )∈A
V1 V2 V3 V4 V5
2 3
8
7 5
5 1 5 11
7 9
o 1 3 4 6 8 10 d
2 5 6 4
12
4 9 9
¡El caso más eficiente es casi 19 veces más rápido que el más lento!
n −1
T (n) = ∑ T (i )T (n − i ), para n > 1
i =1
T (1) = 1 Números de Catalan
1 2n − 2
T (n) =
n n− 1
Por ejemplo:
n 1 2 3 4 5 10 15
T (n) 1 1 2 5 14 4862 2674440
deberán ser realizados de forma óptima para que el total también sea
óptimo.
• Método:
– Construir la matriz [mij], 1≤i≤j≤n, donde mij da el óptimo (i.e., el número
de multiplicaciones escalares requeridas) para la parte
del producto total.
– La solución final vendrá dada por m1n.
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 34
Multiplicación de una secuencia de matrices
– Construcción de [mij], 1≤i≤j≤n:
• Guardar las dimensiones de las Mi, 1≤i≤n, en un vector d, de
0..n componentes, de forma que Mi tiene dimensiones di-1×di.
• La diagonal s de [mij] contiene los mij tales que j-i=s:
– Para s=3:
– La matriz es:
(s = j – i,
es decir,
j = i + s)
– Θ(n3)
• Coste en memoria:
– Θ(n2)
i ?
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 46
Comparaciones de secuencias
algoritmo compSec(ent A:cad[n]; ent B:cad[m];
sal C:vect[0..n,0..m]de nat; sal T:vect[1..n,1..m]de Transf)
{Transf=(borrar,insert,sustit,nada); i.e. posibles transformaciones}
variables i,j,x,y,z:nat
principio
para i:=0 hasta n hacer C[i,0]:=i fpara;
para j:=0 hasta m hacer C[0,j]:=j fpara;
para i:=1 hasta n hacer
para j:=1 hasta m hacer
x:=C[i-1,j]+1; y:=C[i,j-1]+1;
si A[i]=B[j] entonces z:=C[i-1,j-1]
sino z:=C[i-1,j-1]+1
fsi;
C[i,j]:=min(x,y,z);
T[i,j]:= (min=x) => borrar; {último cambio de A[i] a B[j]}
(min=y) => insert;
(min=z) & A[i]=B[j]) => nada;
(min=z) & A[i]≠B[j]) => sustit;
fpara
fpara
Fin
– En tiempo: Θ(nm)
– En espacio: Θ(nm)
• En resumen:
– Se tiene la siguiente ecuación recurrente que define el método
de programación dinámica.
{ }
Dk (i , j) = min Dk − 1(i , j ), Dk − 1(i , k) + Dk − 1(k , j ) ,
k ≥1
D0 (i , j) = C (i , j ), 1≤ i ≤ n, 1≤ j ≤ n
...
para todo k en vért hacer
para todo i en vért hacer
para todo j en vért hacer
si D[i,k]+D[k,j]<D[i,j] entonces
D[i,j]:=D[i,k]+D[k,j]
fsi
fpara
fpara
fpara;
devuelve D
fin
{Post: D=caminosMínimos(g)}
Palabra Probabilidad
• Ejemplo: a 0, 22
qi = 0, 0≤ i ≤ 7 al 0,18
ama 0, 20
eso 0,05
si 0, 25
sin 0,02
Algoritmia básica - Javier Campos (Universidad de Zaragoza) su 0,08 57
Árboles binarios de búsqueda óptimos
si
• Solución 1:
eso • Solución 2:
a su
Creada con
estrategia voraz. Árbol perfectamente
ama sin al sin equilibrado.
C=2,43
al eso a ama si su C=2,70
ama
• Solución 3:
a si
Es óptima.
C=2,15 al eso su
sin
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 58
Árboles binarios de búsqueda óptimos
E.N. Gilbert y E.F. Moore: “Variable length encodings”,
Bell System Technical Journal, 38(4), pp. 933-968, 1959.
{ }
Cij = mij + min Ci , k − 1 + Ckj , si 0≤ i < j ≤ n
i < k≤ j
Cii = 0, si 0≤ i ≤ n
Palabra Probabilidad
a 0, 22
al 0,18
ama
eso
0, 20
0,05 { }
Cij = mij + min Ci , k− 1 + Ckj , si 0≤ i < j ≤ n
i < k≤ j
si 0, 25
sin 0,02 Cii = 0, si 0≤ i ≤ n
su 0,08
0 1 2 3 4 5 6 7
0 0 0,22 0,58 1,02 1,17 1,83 1,89 2,15
7º
1 0 0,18 0,56 0,66 1,21 1,27 1,53
6º
2 0 0,20 0,30 0,80 0,84 1,02
5º
3 0 0,05 0,35 0,39 0,57
C= 4º
4 0 0,25 0,29 0,47
3º
5 0 0,02 0,12
2º
6 0 0,08
1º
7 0
...
para d:=2 hasta n hacer
para j:=d hasta n hacer
i:=j-d;
min:=maxEntero;
para k:=i+1 hasta j hacer
aux:=C[i,k-1]+C[k,j];
si aux<min entonces
min:=aux;
r[i,j]:=k
fsi
fpara;
C[i,j]:=m[i,j]+min
fpara
fpara
fin
∑ (r[i + 1, j ]− r [i , j − 1]+ 1)
d ≤ j ≤n
i = j−d
= r [n − d + 1, n ]− r [0, d − 1]+ n − d + 1< 2n
D1 D2 D3 ••• Dn
– Denotemos:
fi (x) = máximo ∏ φ j (mj )
1≤ j ≤i
sujeto a ∑ cj m j ≤ x
1≤ j ≤i
1≤ mj ≤ u j , 1≤ j ≤ i
f n (c) = max
1 ≤mn ≤u
{
n
φn ( mn ) f n − 1 (c − cn m n ) }
f i (x ) = max
1 ≤ m i ≤ ui
{φ i ( m i ) f i − 1 (x − ci m i ) }
f 0 (x) = 1, para todox , 0≤ x ≤ c
{ }
= min L1j + g( j ,V \ {1, j })
2≤ j ≤n
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 73
El problema del viajante de comercio
– Más en general, si i≠1, S≠Ø e i∉S:
{ }
g (i ,S) = min Lij + g( j ,S \ { j })
j ∈S
(*)
Además:
g (i ,∅) = Li 1, i = 2,3,…, n
– Método de resolución:
• Usar (*) y calcular g para todos los conjunto S con un solo vértice (distinto
del 1).
• Volver a usar (*) y calcular g para todos los conjuntos S de dos vértices
(distintos del 1) y así sucesivamente.
• Cuando se conoce el valor de g para todos los conjuntos S a los que sólo les
falta un vértice (distinto del 1) basta calcular g(1,V \ {1}).
Usar
j ∈S
{
g (i ,S) = min Lij + g( j ,S \ { j }) } para obtener:
{
g (3,{ 2, 4}) = min L32+ g(2,{4}), L24+ g(4,{2}) = }
= min{31,25} = 25;
{
g (4 ,{ 2, 3}) = min L42+ g(2,{3}), L43+ g(3,{2}) =}
= min{23,27} = 23.
– Finalmente:
g (1,{ 2, 3, 4}) = min{ L12+ g(2,{3,4}),
L13+ g(3,{2,4}),
L14 + g(4,{2,3}) } =
= min{ 35,40,43 } = 35.
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 76
El problema del viajante de comercio
• Si además se quiere saber cómo se construye el circuito óptimo:
Utilizar una función adicional
J(i,S) es el valor de j que minimiza g(i,S) al aplicar la fórmula (*).
• En el ejemplo:
J(2,{3,4}) = 4; J(3,{2,4}) = 4;
J(4,{2,3}) = 2; J(1,{2,3,4}) = 2.
n− 2
Tiempo de cálculo:
k= 1
k (
Θ 2(n − 1) + ∑ (n − 1)k n − 2 = Θ n22n )
r
puesto que ∑ k rk = r 2r − 1
k= 1
20 2, 43 × 10 18 419.430.400 20.971.520
más de 77.000 años
25 1, 55 × 10 25 20.971.520.000 838.860.800
30 2, 65 × 10 32 966.367.641.600 32.212.254.720
50 3, 04 × 10 64 2, 81 × 10 18 5, 62 × 10 16
(a)
(b)
{
F (S) = max fi (S)
1≤i ≤n
}
– El tiempo medio de terminación, MFT(S), se define como:
1
MFT(S) = ∑ fi (S)
n 1≤i ≤n
– Principio de optimalidad:
0 t+bi-ai
ai aj, j∈S\{i}
bi bj, j∈S\{i}
0 bi
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 88
Planificación de trabajos
– La ecuación recursiva resultante podría resolverse de forma análoga a la
del problema del viajante de comercio, pero existe una solución mejor…
– Supongamos que i y j son los dos primeros trabajos (y en ese orden) en la
planificación óptima del subconjunto S; entonces:
= bj + bi − aj + max{max{t − ai ,0}, aj − bi } =
= bj + bi − aj + max{t − ai , aj − bi ,0} =
= bj + bi − aj − ai + max{t, ai + aj − bi , ai }
Es decir:
ai + aj + max{− bi ,− aj } ≤ aj + ai + max{− bj ,−ai }
O sea:
min{bi ,a j } ≥ min{bj , ai } (*)
– Luego existe una planificación óptima en la que cada par (i,j) de trabajos
adyacentes verifica (*).
– Puede demostrarse que todas las planificaciones que verifican (*) tienen la
misma longitud.
Por tanto, basta generar una permutación para la que se cumpla (*) para
todo par de trabajos adyacentes.
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 90
Planificación de trabajos
– Ahora, si
n
– Por tanto, el tiempo para calcular P(n,n) es Ω( 2 )
n
y puede demostrarse que 2n 2n
≥2 (2n + 1)
n
1 2 21 32 13 16 15 16 1 4
11 32 1 2 11 16 7 8 1 3 P(i,j) = pP(i-1,j) + qP(i,j-1)
3 16 5 16 1 2 3 4 1 2
j
1 16 1 8 1 4 1 2 1 1
0 0 0 0 0
4 3 2 1 0
i
la matriz se completa, por ejemplo,
por filas (de abajo a arriba, j=0, 1, …, n)
y en cada fila por columnas (de dch. a izq., i=0, 1, …, n)
– En tiempo: Θ(n2)
v2 v3
v1 v4
S65
v5
v0
v6
v2 v3
3. Para algún k entre 2 y s-3, S13
tomar el vértice vi+k y formar v1
un triángulo con lados
(vi,vi+k), (vi+k,vi+s-1) y (vi,vi+s-1), S65
S63
y después resolver los
subproblemas Si,k+1 y Si+k,s-k. v0
v6
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 103
Triangulación de polígonos
– Por tanto, si denotamos por Cis el coste de la triangulación Sis,
se obtiene la siguiente relación recursiva:
Cis = min
1≤k ≤s −2
{
Ci , k + 1 + Ci + k , s − k + D(vi ,vi + k ) +
+ D(vi + k ,vi + s − 1 ) }
para 0≤i≤n-1, 4≤s≤n;
donde:
D(vp,vq) es la longitud de la cuerda entre los vértices vp y vq si
vp y vq no son vértices adyacentes en el polígono;
y D(vp,vq) es 0 si vp y vq son adyacentes.
• Solución eficiente:
– Utilización de una tabla para almacenar los costes de las soluciones de los
subproblemas
v6
– El valor de C06 procede de k=2. Por tanto, el problema se divide en S03 y S24.
S03 es un triángulo con vértices v0, v1 y v2, luego no precisa ser resuelto, mientras
que S24 es un cuadrilátero, definido por v2, v3, v4 y v5, y debe ser resuelto.
Además, hay que incluir los costes de las cuerdas (v0,v2) y (v2,v5), que son 17’89 y
19’80.
– El valor de C24 se obtiene con k=1, dando los subproblemas S22 y S33, que tienen
tamaño menor o igual que tres y, por tanto, coste 0.
Se introduce la cuerda (v3,v5), con coste 15’65.
– Existen otros problemas en los que no hay más remedio que buscar.
– Por lo tanto, toda solución del problema puede representarse con una
8-tupla (x1,…,x8) en la que xi es la columna en la que se coloca la reina
que está en la fila i del tablero.
x3= 3 4 2 4 2 3 3 4 1 4 1 3 2 4 1 4 1 2 2 3 1 3 1 2
4 6 9 11 14 16 20 22 25 27 30 32 36 38 41 43 46 48 52 54 57 59 62 64
4 4 4 3 3 2
x4= 4 4 3 4 3 2
2
3 2 2 3 1 1 2 1 2 1 1
5 7 10 12 15 17 21 23 26 28 31 33 37 39 42 44 47 49 53 55 58 60 63 65
– Por tanto, los candidatos para xi+1 son los valores de G tales que satisfacen
A.
...
La llamada inicial es:
buscarSol(1,solución);
...
x1=1 x1=2
2 18
x3 = 2 4 2 3 1
9 11 14 16 30
x4 = 3 3
(e) (f) (g) (h) 15 31
– Backtracking =
...
colocarReinas(1,sol);
...
i j xi x j
k
wxi M
i1 (para evitar generar varias
xi xi 1, 1 i n instancias de la misma tupla)
• Conclusión:
– Pueden existir varias formas de formular un problema, con distintas
representaciones de las soluciones (aunque siempre verificando éstas un
conjunto de restricciones explícitas e implícitas).
x1=1 x1=4
x1=2
x1=3
2 3 4 5
16
...
{Generación del hijo derecho y evaluación de Bk}
si (s+r-w[k]M) and (s+w[k+1]M) entonces {Bk =verdad}
x[k]:=0;
sumasub(s,k+1,r-w[k])
fsi
fin
C
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 36
Coloreado de grafos
• Problema de decisión:
– Dados un grafo G y un número entero positivo m, ¿es G m-coloreable?
– Es decir, ¿se puede pintar con colores los nodos de G de modo que no
haya dos vértices adyacentes con el mismo color y se usen sólo m colores?
• Problema de optimización:
– Dado un grafo G, ¿cuál es su número cromático?
– Es decir, ¿cuál es el menor número m de colores con el que se puede
colorear G?
x[1]=1 x[1]=3
x[1]=2
x[2]=1 x[2]=3
x[2]=2
x[3]=
x[3]=1
3
x[3]
=2
Grado m y altura n.
Cada nodo de nivel i tiene m hijos que corresponden a las m posibles
asignaciones a x[i], 1in.
...
{g contiene la matriz de adyacencia del grafo}
para i:=1 hasta n hacer
x[i]:=0
fpara;
m_coloreado(1,x);
...
O (mn )
• viV, i=1,…,n+1,
• (vi,vi+1)A, i=1,…,n,
• v1=vn+1,
1 2 3 4
8 7 6 5
Hamiltoniano: 1-2-8-7-6-5-4-3-1
1 2 3
5 4
No contiene ningún hamiltoniano.
• k=1: x1 puede ser cualquiera de los n vértices, pero para evitar escribir el
mismo ciclo n veces obligamos que x1=1;
• k=n: xn sólo puede ser el vértice que queda sin visitar y debe estar conectado
por sendos arcos con x1 y xn-1.
...
{g contiene la matriz de adyacencia del grafo}
x[1]:=1;
para i:=2 hasta n hacer
x[i]:=0
fpara;
hamiltoniano(2,x);
...
...
lab[x,y]:=camino;
si (x=n)(y=n) entonces {se ha encontrado una solución}
encontrado:=verdad
sino
ensayar(x+1,y,lab,encontrado);
si not encontrado entonces ensayar(x,y+1,lab,encontrado) fsi;
si not encontrado entonces ensayar(x-1,y,lab,encontrado) fsi;
si not encontrado entonces ensayar(x,y-1,lab,encontrado) fsi;
si not encontrado entonces lab[x,y]:=imposible fsi
fsi
fsi
fsi
fin
1 2 3 4 5 6 7 8
1
2
3
4
5
6
7
8
4 1
3 2
...
si éxito entonces
para i:=1 hasta n hacer
para j:=1 hasta n hacer
escribir(tab[i,j]);
fpara;
escribirLínea
fpara
sino
escribir(‘No hay solución’)
fsi
fin
algoritmo caballo
constante n=8
variables dx,dy:vector[1..8] de entero;
tab:vector[1..n,1..n] de entero;
x,y,i,j,k,kk,u,v,num,menor:entero; parar:booleano
principio
dx[1]:=2; dx[2]:=1; dx[3]:=-1; dx[4]:=-2;
dx[5]:=-2; dx[6]:=-1; dx[7]:=1; dx[8]:=2;
dy[1]:=1; dy[2]:=2; dy[3]:=2; dy[4]:=1;
dy[5]:=-1; dy[6]:=-2; dy[7]:=-2; dy[8]:=-1;
para i:=1 hasta n hacer
para j:=1 hasta n hacer
tab[i,j]:=0
fpara;
fpara;
escribir(‘Introduce x inicial:’); leer(x);
escribir(‘Introduce y inicial:’); leer(y);
tab[x,y]:=1; i:=1; parar:=falso;
...
...
mq (i<n*n) and not parar hacer
i:=i+1; menor:=9;
para k:=1 hasta 8 hacer
u:=x+dx[k]; v:=y+dy[k];
si (1u)(un)(1v)(vn) entonces
si tab[u,v]=0 entonces
num:=accesibles(u,v);
si num<menor entonces menor:=num; kk:=k fsi
fsi
fsi
fpara;
si menor=9 entonces
parar:=verdad
sino
x:=x+dx[kk]; y:=y+dy[kk]; tab[x,y]:=i
fsi
fmq;
...
...
si not parar entonces
para i:=1 hasta n hacer
para j:=1 hasta n hacer
escribir(tab[i,j])
fpara;
escribirLínea
fpara
sino
escribir(‘No encuentro solución’)
fsi
fin
Introduce i inicial: 1
Introduce j inicial: 3
23 6 1 16 21
12 17 22 7 2
5 24 11 20 15
10 13 18 3 8
25 4 9 14 19
con xi {0,1}, bi 0, pi 0, 1 i n
x1=4
xi=objeto introducido en i-ésimo lugar x1=1
x1=2
x1=3
2 10 14 16
x2=3 x2=4
x2=2 x2=4
x2=3 x =4
2
3 7 9 11 13 15
4 6 8 12
x4=4
2 17
3 10 18 25
4 7 11 14 19 22 26 29
x4=1 x4=1 x4=1 x4=1 x4=1 x4=1
x4=1 x4=1
x4=0 x4=0 x4=0 x4=0 x4=0
x4=0 x4=0 x4=0
5 6 8 9 12 13 15 16 20 21 23 24 27 28 30 31
{Pre: i1..n:peso[i]>0
i1..n-1:benef[i]/peso[i]benef[i+1]/peso[i+1]}
función cota(benef,peso:vectReal; cap,ben:real; obj:entero)
devuelve real
{cap=capacidad aún libre de la mochila;
ben=beneficio actual;
obj=índice del primer objeto a considerar}
principio
si obj>n or cap=0.0 entonces devuelve ben
sino
si peso[obj]>cap entonces devuelve ben+cap/peso[obj]*benef[obj]
sino
devuelve cota(benef,peso,cap-peso[obj],ben+benef[obj],obj+1)
fsi
fsi
fin
139 ben=159
149 151 159 sol=(1,1,1,0,1,1,0,0)
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 82
El problema de la mochila 0-1
– De los 29 – 1 ( = 511) nodos del espacio de estados, sólo se generaron 33.
sujeto a pi xi C (*)
1 i n
con 0 xi 1, 1 i n
• Si la solución es entera (0-1), también es óptima para el problema 0-1.
• Si no es entera, existe exactamente un xi tal que 0<xi<1.
Se parte el espacio de soluciones en dos subespacios: en uno (subárbol
izquierdo) xi=0 y en otro (subárbol derecho) xi=1.
– En general, en cada nodo del árbol, se usa el algoritmo voraz para
resolver el pb. (*) con las restricciones añadidas correspondientes a las
asignaciones ya realizadas a lo largo del camino desde la raíz al nodo.
• Si la solución es entera, ya se tiene el óptimo para ese nodo.
• Si no lo es, existe exactamente un xi tal que 0<xi<1, etc.
x1=0 x6=10
D={1,2,2,2,3,3,3,4,5,5,5,6,7,8}
– La distancia mayor restante es 8, luego x2=2 ó x5=8. Por simetría, puede
observarse que ambas elecciones dan una misma solución (en realidad,
una da la imagen especular de la otra) o no dan solución. Tomamos x5=8.
– Se borran las distancias x6 – x5 = 2 y x5 – x1 = 8 de D.
Retroceso...
x5=8
x4=7** x2=3
x3=5
(*) indica que los puntos elegidos son inconsistentes con las distancias dadas
(**) indica que ese nodo tiene dos nodos imposibles como hijos (luego es un
camino incorrecto)
el coste es O(n2log n)
Sin embargo:
• ¡ No se conoce ningún ejemplo en el que el número de retrocesos sea mayor
que O(1) !
– Los niveles impares del árbol están asociados con las configuraciones en
las que debe jugar uno de los dos jugadores, mientras que los niveles
pares se asocian a las configuraciones en las que debe jugar el otro.
– Por ejemplo, una función de utilidad habitual toma tres valores posibles:
• “configuración ganadora”,
• “configuración perdedora” y
• “configuración empatadora o nula”.
– Interpretación:
Situación (o posibilidades) que tiene el jugador (tomamos partido por uno
de ellos) en esa configuración, suponiendo que ninguno de los dos
jugadores se equivocará y ambos realizarán en lo sucesivo la mejor jugada
posible.
•
•
– Llamaremos a los dos •
• •
• •
por ejemplo,
que empieza “yo”. yo yo yo yo yo yo yo
nivel 7 yo él 1 yo yo él -1 yo él 0
– El árbol tiene la mueve “él”
él él él él él yo él
yo él yo yo yo yo él yo yo yo
nivel 8 yo yo él 0 yo yo él -1 yo él 0 él yo él 1
mueve “yo” él él él él él él yo él él yo él
GANA “él”
yo él yo yo él yo yo yo yo
nivel 9 yo yo él 0 yo yo él 0 él yo él 1
él yo él él yo él él yo él
...
mq not esLaUltimaJug(c,i) hacer
i:=i+1;
jugada(c,i,unaJugada);
si juegoYo entonces
laUtilidad:=max(laUtilidad,utilidad(unaJugada,falso))
sino
laUtilidad:=min(laUtilidad,utilidad(unaJugada,verdad))
fsi
fmq;
devuelve laUtilidad
fsi
fin
d
15
– Este ahorro es muy grande y supone que las búsquedas que usan la poda
pueden ir al doble de la profundidad en comparación con un árbol no
podado.
es decir,
• El problema original:
1 2 3 4 1 2 3 4
5 6 7 8
? 5 6 7 8
9 10 11 12 9 10 11 12
13 15 14 13 14 15
16
∑ m(i) + x es par
i =1
– Para el ejemplo anterior, dicha función vale 16, luego el estado objetivo es
alcanzable.
6 → ←7 8 ↑ ↓ 9 10 → 11 ↓ ← 12 13 ↑ 14 ↓ ← 15
1 2 4 1 2 4 1 2 3 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 3 4 1 2 3 4 1 2 3 4
5 6 3 8 5 6 3 8 5 6 8 4 5 6 8 11 5 6 7 8 5 6 7 8 5 6 7 8 5 2 6 8 5 10 6 8 5 6 8
9 10 7 11 9 10 7 11 9 10 7 11 9 10 7 9 10 11 9 10 15 11 9 10 11 9 10 7 11 9 7 11 9 10 7 11
13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12
16 ↓ 19 ← ↓ ← 22 ↑ ↓ 23
1 2 4 8 ↓ ← 1 2 3 1 2 3 4 1 2 3 4
5 6 3 5 6 8 4 5 6 7 5 6 7 8
9 10 7 11 9 10 7 11 9 10 11 8 9 10 11 12
13 14 15 12 13 14 15 12 13 14 15 12 13 14 15
18 20 21 objetivo
17 1 6 2 4 1 2 4 1 2 3 4 1 2 3 4
5 3 8 5 6 3 8 5 6 8 11 5 6 8 11
9 10 7 11 9 10 7 11 9 10 7 12 9 10 7
13 14 15 12 13 14 15 12 13 14 15 13 14 15 12
12 11 10 9 8 7 ←
1 2 8 11 1 2 8 1 2 8 1 2 4 8 1 2 4 8 1 2 4 8
5 6 4 5 6 4 11 5 6 4 11 5 6 11 5 6 3 11 5 6 3 11
9 10 3 12 9 10 3 12 9 10 3 12 9 10 3 12 9 10 12 9 10 7 12
13 14 7 15
↓ 13 14 7 15 → 13 14 7 15 ↑ 13 14 7 15 ↑ 13 14 7 15 ↑ 13 14 15
…
• sigue la rama izquierda del árbol
• no encuentra nunca la solución (a menos que exista una solución en esa rama)
– LIFO = D-búsqueda
• problemas similares al recorrido en profundidad
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 12
Un primer ejemplo: El juego del 15
• Estrategias no ciegas
c(x) = longitud desde la raíz hasta el estado objetivo más cercano que es
descendiente de x
6 → ←7 8 ↑ ↓ 9 10 → 11 ↓ ← 12 13 ↑ 14 ↓ ← 15
1 2 4 1 2 4 1 2 3 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 3 4 1 2 3 4 1 2 3 4
5 6 3 8 5 6 3 8 5 6 8 4 5 6 8 11 5 6 7 8 5 6 7 8 5 6 7 8 5 2 6 8 5 10 6 8 5 6 8
9 10 7 11 9 10 7 11 9 10 7 11 9 10 7 9 10 11 9 10 15 11 9 10 11 9 10 7 11 9 7 11 9 10 7 11
13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 12 13 14 15 12 13 14 15 12 13 14 15 12 13 14 15 12
16 ↓ 19 ← ↓ ← 22 ↑ ↓ 23
1 2 4 8 ↓ ← 1 2 3 1 2 3 4 1 2 3 4 – Método:
5 6 3 5 6 8 4 5 6 7 5 6 7 8
9
13
10
14
7 11
15 12
9
13
10 7 11
14 15 12
9
13
10
14
11 8
15 12
9
13
10
14
11 12
15
c(23)=3 • la raíz es el nodo en curso
• generar sus hijos hasta encontrar uno
18 20 21 objetivo
17 1 6 2 4 1 2 4 1 2 3 4 1 2 3 4 con igual valor de c que él (en el
5 3 8 5 6 3 8 5 6 8 11 5 6 8 11
9 10 7 11 9 10 7 11 9 10 7 12 9 10 7
ejemplo, 4)
13 14 15 12 13 14 15 12 13 14 15 13 14 15 12
• repetir lo mismo (en el ejemplo, 10)
• hasta encontrar el objetivo (en el
ejemplo, 23)
Los únicos nodos en curso son los del
camino desde la raíz hasta la solución
más cercana.
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 14
Un primer ejemplo: El juego del 15
– Problema: el cálculo de la función c.
– Un ejemplo de problemas en los que es posible: aquéllos en los que hay
soluciones voraces.
– En general, usar una función de estimación: cˆ (x) = f (x) + gˆ (x),
con f(x) = longitud del camino de la raíz a x
y gˆ (x) = estimación de la longitud del camino desde x hasta la
solución más cercana
10 1 2 3 4 11 1 2 3 4
12 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8
9 10 11 9 10 15 11 9 10 11
13 14 15 12 13 14 12 13 14 15 12
2 1 2 4
3
1 2 3 4
5
1 2 3 4
11 1 2 3 4
5 6 3 8 5 6 8 5 6 8 5 6 7 8
9 10 7 11 9 10 7 11 9 10 7 11 9 10 15 11
13 14 15 12 13 14 15 12 13 14 15 12 13 14 12
12 1 2 3 4
5 6 7 8
22 1
5
2
6
3 4
7
23 1
5
2
6
3 4
7 8
9 10 11 9 10 11 8 9 10 11 12
13 14 15 12 13 14 15 12 13 14 15
– Se utiliza una función de estimación cˆ (x) que sea una cota inferior de
todas las soluciones obtenidas desde x:
cˆ (x) ≤ c(x)
– cada vez que se añade un nodo a la cola, hay que guardar en una tabla
auxiliar de padres de nodos ese nodo junto a su padre o bien guardar con
cada nodo una identificación de su padre, y
– hay que mantener una variable auxiliar con el valor del último nodo
solución que ha permitido actualizar U.
2 3 4 5
• Nodos cuadrados: x2=4
estados no factibles x2=2 x2=3 x2=4 x2=4
x2=3
6 7 8 9 10 11
• Nodos circulares:
nodos factibles x3=3 x3=4 x3=4 x3=4
(o soluciones)
12 13 14 15
• Nodo 9:
solución óptima (es la única)
S = {2,3}
Penalización total = 8
4 5 6 7
x3=1 x3=0 x3=1 x3=0
9 10 11 12 13 14 15
x4=1 x4=0
• Solución óptima:
19 21 23 25 26 27 28 29 30 31
nodo 25
S = {2,3}
Penalización total = 8
12 13 14 15 (t1,d1,w1) = (1,1,5)
c=∞ c=∞ c=∞ c=∞ (t2,d2,w2) = (2,3,10)
(t3,d3,w3) = (1,2,6)
(t4,d4,w4) = (1,1,3)
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 35
Un problema de planificación de tareas a plazo fijo
• Definición de la función de coste c(x).
Caso de representación de tamaño fijo:
– Para todo nodo circular x con algún hijo circular: c(x) = mínima
penalización correspondiente a todos los nodos descendientes de x.
– Para todo nodo cuadrado x: c=8 1
c(x) = ∞. x1=1 x1=0
c=9 2 c=8 3
x2=1 x2=0 x2=1 x2=0
c=9 4 c = 13 5 c=8 6 c = 15 7
(t1,d1,w1) = (1,1,5)
x3=1 x3=0 x3=1 x3=0
(t2,d2,w2) = (2,3,10)
c = 13 c = 19 c = 8 c = 11 c = 15 c = 21
(t3,d3,w3) = (1,2,6) c=9
9 10 11 12 13 14 15
(t4,d4,w4) = (1,1,3)
x4=1 x4=0
19 21 23 25 26 27 28 29 30 31
9 13 19 8 11 14 15 18 21 24
Algoritmia básica - Javier Campos (Universidad de Zaragoza) 36
Un problema de planificación de tareas a plazo fijo
• Definición de una función de estimación:
cˆ (x) ≤ c(x)
– Sean
• Sx = {tareas seleccionadas para S hasta el nodo x}
• mx = max {i | i ∈ Sx}
– Entonces:
penalización debida
cˆ (x) = ∑ wi a las tareas que ya
i <m x
i ∉Sx han quedado
excluidas de x
x1=1 x1=4
x1=2 x1=3
cˆ = 0 2 cˆ = 5 3 cˆ = 15 4 5
cˆ = 21
x2=2 x2=4 x2=3 x2=4
x2=3 x2=4
cˆ = 0 6 cˆ = 10 7 8 9 10 11 cˆ = 15
cˆ = ∞ cˆ = 5 cˆ = 11
x3=3 x3=4 x3=4 x3=4
12 13 14 15
cˆ = ∞ cˆ = ∞ cˆ = ∞ cˆ = ∞
(t1,d1,w1) = (1,1,5)
cˆ (x) = ∑ wi (t2,d2,w2) = (2,3,10)
i <m x (t3,d3,w3) = (1,2,6)
i ∉Sx
(t4,d4,w4) = (1,1,3)
cˆ = 0 2 cˆ = 5 3
x2=1 x2=0 x2=1 x2=0 cˆ (x) = ∑ wi
i <m x
cˆ = 0 4 cˆ = 10 5 cˆ = 5 6 cˆ = 15 7 i ∉Sx
cˆ = 6 cˆ = 10 cˆ = 16 cˆ = 5 cˆ = 11 cˆ = 15 cˆ = 21
9 10 11 12 13 14 15 (t1,d1,w1) = (1,1,5)
(t2,d2,w2) = (2,3,10)
x4=1 x4=0
(t3,d3,w3) = (1,2,6)
19 21 23 25 26 27 28 29 30 31 (t4,d4,w4) = (1,1,3)
9 13 19 8 11 14 15 18 21 24
– Definición de U:
(Recordar:
U debe ser cota superior del coste de una solución de mínimo coste)
U = ∑ wi
i ∉Sx
tamaño variable) cˆ = 0 cˆ = 5 cˆ = 15 4 cˆ = 21 5
2 U = 14 3
U = 19 U = 18 U = 21
x2=4 x2=3 x2=4
x2=2 x2=4
(t1,d1,w1) = (1,1,5) x2=3
(t2,d2,w2) = (2,3,10) 6 7 8 9 10 11
(t3,d3,w3) = (1,2,6)
x3=3 x3=4 x3=4 x3=4
(t4,d4,w4) = (1,1,3)
12 13 14 15
U = ∑ wi
i ∉Sx
12 13 14 15 U= ∑ wi
cˆ = ∞ cˆ = ∞ cˆ = ∞ i ∉Sx
– El siguiente nodo en curso es 2 . (cˆ (2) = 0 < 5 = cˆ (3) )
– Se añaden a la cola: 6 , 7 , 8 . Se actualiza U a 9 al generar 6 .
– El nodo 7 se mata porque cˆ (7) = 10 > U = 9.
– El nodo 8 se mata porque no es factible.
– Los nodos vivos son 3 y 6 . El siguiente nodo en curso es 6 .
sujeto a ∑ pi xi ≤ C
1≤i ≤n
{ }
con xi ∈ 0,1 , bi > 0, pi > 0, 1 ≤ i ≤ n
1
• Espacio de soluciones: x1=0 x1=1
– 2n
modos de asignar los
2 17
valores 0 ó 1 a las xi.
x2=0 x2=1 x2=0 x2=1
– Dos formas de representar
3 10 18 25
la solución: tuplas de
tamaño fijo o variable. x3=0 x3=1 x3=0 x3=1 x3=0 x3=1 x3=0 x3=1
4 7 11 14 19 22 26 29
∑ pi xi > C
1≤i ≤n
– Para nodos x que no sean hojas, c(x) es el mínimo entre c(xiz) y c(xde),
siendo xiz y xde los hijos izquierdo y derecho, resp., de x.
• Valor U:
– Solución más sencilla:
Si x es un nodo de nivel j, con 0≤j≤n, se han asignado ya valores a xi,
1≤i≤j, por tanto:
c(x) ≤ − ∑ bi xi = U
1 ≤i ≤ j
cˆ (4) =−38
4 Siguiente nodo en curso. Se expande…
U = −32 4
x3=1 x3=0
cˆ (6) =−38 cˆ (7) =−38
6 7
U = −32 U = −38
¿Siguiente nodo en curso?
Hay dos con igual prioridad: 6 y 7.
Si es elegido el 6, se generan sus hijos: el izquierdo es eliminado por no ser factible,
el derecho se añade a la cola de vivos (con prioridad -32, mayor que el nodo 7),
luego el siguiente elegido es el 7.
n = 4;
7 Siguiente nodo en curso. (b1,b2,b3,b4) = (10,10,12,18)
Nuevo valor de U = -38. Se expande… (p1,p2,p3,p4) = (2,4,6,9)
C = 15
cˆ (7) =−38
U = −38 7
x4=1 x4=0
cˆ (8) =−38 cˆ (9) =−20
8 9
U = −38 U = −20
– Ya en el año 85…
E.L. Lawler, J.K. Lenstra,
A.H.G. Rinnooy Kan, y D.B. Shmoys:
The Traveling Salesman Problem.
John Wiley & Sons, New York, 1985.
2 3 4
5 6 7 8 9 10
11 12 13 14 15 16
– Debe ser tal que el nodo solución x con valor mínimo de c(x) corresponda
a un recorrido de longitud mínima.
– Por ejemplo,
i1=2
i2=3 i2=4
cˆ (6) = L1, 2 + L2, 4
5 6
cˆ (x) = c(x)
• Inicialmente, U = ∞.
i1 = 2 i1 = 5
i1 = 3 i1 = 4
cˆ = 35 2 cˆ = 53 3 cˆ = 25 4 cˆ = 31 5
i2 = 2 i2 = 5
i2 = 3
cˆ = 28 6 7 8 cˆ = 36
cˆ = 50
i3 = 3 El siguiente nodo en curso sería
i3 = 5
el 5, pero cˆ (5) = 31 > U
cˆ = 32 9 10 cˆ = 28 luego el algoritmo
termina y el hamiltoniano mínimo
i4 = 3 es 1,4,2,5,3,1.
cˆ = 28 11 Es hoja (solución),
se actualiza U = 28.
3 2 1
incluir excluir
1 (1,3) (1,3)
incluir excluir
(1,2) (1,2) 2 3
incluir excluir incluir excluir
2 3 (1,2) (1,2) (1,2) (1,2)
incluir excluir incluir excluir 4 5 6 7
(1,3) (1,3) (1,3) (1,3)
4 5 6 7
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
Outline
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
Introduction
Linear Programming
Assign real values to a set of given variables so as to:
Satisfy a set of linear equations and/or linear inequalities.
Maximize or minimize a given linear objective function.
Introduction
Linear Programming
Assign real values to a set of given variables so as to:
Satisfy a set of linear equations and/or linear inequalities.
Maximize or minimize a given linear objective function.
Example: Chocolates
———————————————————————–
Example: Chocolates
Objetive function max x1 + 6x2
Constraints x1 ≤ 200
x2 ≤ 300
x1 + x2 ≤ 400
x1 , x2 ≥ 0
———————————————————————–
Example: Chocolates
Goal
Find the point of this polygon at which the objective function is
maximized.
Example: Chocolates
Remark
Given that the constraints define a convex set and the objective
function is linear, the optimum solution is always achieved at a vertex.
Two exceptions:
The linear program is infeasible (it is impossible to satisfy all
constraints):
x ≤ 1, x ≥ 2
The linear program is unbounded:
max x1 + x2
x1 ≥ 2
x2 ≤ 3
Example: Chocolates
Linear Programs (LP) can be solved by the simplex algorithm (Dantzig, 1947).
Main idea
The algorithm starts at a given
vertex (in our case (0, 0)).
It repeatedly looks for an
adjacent vertex of better
objective value.
It stops when no better
adjacent vertex exists. The last
visited vertex is globally
optimum.
Example: Chocolates
The chocolatier introduces a third product: Cakes. Updated table
Product Variable Profit Max. demand
Muffins x1 1 200
Chocolates x2 6 300
Cakes x3 13 –
The sum of all three variables can be at most 400.
Packaging constraints impose that x2 + 3x3 ≤ 600.
———————————————————————–
Updated linear program:
max x1 + 6x2 + 13x3
x1 ≤ 200
x2 ≤ 300
x1 + x2 + x3 ≤ 400
x2 + 3x3 ≤ 600
x1 , x2 , x3 ≥ 0
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 10 / 71
Introduction
Example: Chocolates
Example: Chocolates
Example: Chocolates
Updated linear program:
Let’s add the second inequality to the third. Then, add to the result the
fourth inequality multiplied by 4. The result is the inequality:
x1 + 6x2 + 13x3 ≤ 3100
Hence, no feasible solution can have a profit greater than 3100.
———————————————————————–
Example: Chocolates
Updated linear program:
Let’s add the second inequality to the third. Then, add to the result the
fourth inequality multiplied by 4. The result is the inequality:
x1 + 6x2 + 13x3 ≤ 3100
Hence, no feasible solution can have a profit greater than 3100.
———————————————————————–
What if we add a fourth line of chocolates, or hundreds more of them?
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 13 / 71
Introduction
Constraints
Variables must be nonnegative: wi , xi , oi , hi , fi , si ≥ 0, i = 1, . . . , 12
Number of carpets per month (regular production plus overtime):
xi = 20wi + oi , i = 1, . . . , 12
Number of workers at the start of each month:
wi = wi−1 + hi − fi , i = 1, . . . , 12
Number of carpets stored at the end of each month:
si = si−1 + xi − di , i = 1, . . . , 12
At most 30 % overtime is allowed: oi ≤ 6wi , i = 1, . . . , 12
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 15 / 71
Introduction
Variables
Constraints
12
X 12
X 12
X 12
X 12
X
min 2000 wi + 320 hi + 400 fi + 8 si + 180 oi
i=1 i=1 i=1 i=1 i=1
Done!
Variables
Constraints
12
X 12
X 12
X 12
X 12
X
min 2000 wi + 320 hi + 400 fi + 8 si + 180 oi
i=1 i=1 i=1 i=1 i=1
Done!
———————————————————————–
Reductions
Reduction: Transformation of one problem into another problem.
Reductions
Reduction: Transformation of one problem into another problem.
———————————————————————–
Reductions enhance the power of algorithms...especially true for LPs.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 19 / 71
Introduction
———————————————————————–
s≥0
Pn s≥0
Equality constraint like i=1 ai xi = b to inequality. Substitute the equality by:
n
X
ai xi ≥ b
i=1
n
X
ai xi ≤ b
i=1
Pn s≥0
Equality constraint like i=1 ai xi = b to inequality. Substitute the equality by:
n
X
ai xi ≥ b
i=1
n
X
ai xi ≤ b
i=1
Variable unrestricted in sign like x to nonnegative: Introduce two nonnegative
variables, x + , x − ≥ 0, and replace x by x + − x − .
Pn s≥0
Equality constraint like i=1 ai xi = b to inequality. Substitute the equality by:
n
X
ai xi ≥ b
i=1
n
X
ai xi ≤ b
i=1
Variable unrestricted in sign like x to nonnegative: Introduce two nonnegative
variables, x + , x − ≥ 0, and replace x by x + − x − .
———————————————————————–
Standard form: All variables are nonnegative, the constraints are all
equations, the objective function is to be minimized.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 21 / 71
Introduction
Outline
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
Constraints
Each pipeline has a maximum capacity.
Storing is not possible.
Objective function
X
max fsu
(s,u)∈E
Optimality
Simplex provides a short proof ot the optimality of its solution.
———————————————————————–
Let us partition the nodes of the network into two groups:
No flow can exceed the total capacity of the edges from L to R...
... the solution must be optimal.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 32 / 71
Flows in networks
Optimality
Max-flow min-cut theorem
The size of the maximum flow in a network equals the capacity of the
smallest (s, t)-cut.
Efficiency
———————————————————————–
Efficiency
———————————————————————–
Bipartite matching
Perfect matching:
Bipartite matching
Perfect matching:
Bipartite matching
Perfect matching: Reduction to a maximum-flow problem.
1 Create a new source node, s, connect it to all boys.
2 Connect all girks to a new sink node, t.
3 Associate a capacity of 1 to each edge.
There is a perfect matching iff this network has a flow whose size
equals the number of couples.
———————————————————————–
What if the flow of one edge is 0.52?
Bipartite matching
Perfect matching: Reduction to a maximum-flow problem.
1 Create a new source node, s, connect it to all boys.
2 Connect all girks to a new sink node, t.
3 Associate a capacity of 1 to each edge.
There is a perfect matching iff this network has a flow whose size
equals the number of couples.
———————————————————————–
What if the flow of one edge is 0.52? If all capacities are integers,
then the optimal flow found by our algorithm is integral.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 36 / 71
Duality
Outline
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
Duality
Similarly to the maximum-flow – minimum cut problems...
Every maximization problem has a dual minimization problem.
Duality
Similarly to the maximum-flow – minimum cut problems...
Every maximization problem has a dual minimization problem.
Duality
Similarly to the maximum-flow – minimum cut problems...
Every maximization problem has a dual minimization problem.
x1 + 6x2 ≤ 1900
This is a certificate of optimality!
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 38 / 71
Duality
Duality
Where do these multipliers come from?
Mutiplier Inequality
y1 x1 ≤ 200
y2 x2 ≤ 300
y3 x1 + x2 ≤ 400
These yi ’s must be nonnegative (otherwise ≤ becomes ≥). After multiplying
and summing:
(y1 + y3 )x1 + (y2 + y3 )x2 ≤ 200y1 + 300y2 + 400y3
We want the left-hand side to look like our objective function x1 + 6x2 . That is,
we’d like (y1 + y3 ) to be at least 1 and (y2 + y3 ) to be at least 6.
Duality
Where do these multipliers come from?
Mutiplier Inequality
y1 x1 ≤ 200
y2 x2 ≤ 300
y3 x1 + x2 ≤ 400
These yi ’s must be nonnegative (otherwise ≤ becomes ≥). After multiplying
and summing:
(y1 + y3 )x1 + (y2 + y3 )x2 ≤ 200y1 + 300y2 + 400y3
We want the left-hand side to look like our objective function x1 + 6x2 . That is,
we’d like (y1 + y3 ) to be at least 1 and (y2 + y3 ) to be at least 6.
———————————————————————–
Upper bound for the objective value:
y1 , y2 , y3 ≥ 0
x1 + 6x2 ≤ 200y1 + 300y2 + 400y3 if y1 + y3 ≥ 1
y2 + y3 ≥ 6
Duality
A new LP!
Any feasible value of this dual LP is an upper bound on the original primal LP.
Duality
A new LP!
Any feasible value of this dual LP is an upper bound on the original primal LP.
If we find a pair of primal and dual feasible values that are equal, then they must both
be optimal.
Primal: (x1 , x2 ) = (100, 300); Dual: (y1 , y2 , y3 ) = (0, 5, 1)
They both have value 1900. Optimality is certified.
Duality
Primal LP: Dual LP:
max cT x min yT b
Ax ≤ b yT A ≥ cT
x≥0 y≥0
Duality
Most general case of LP:
n variables
I: set of inequalities
E: set of equalities
N: subset of nonnegative variables
Primal LP: Dual LP:
Duality theorem
If a linear program has a bounded optimum, then so does its dual, and
the two optimum values coincide.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 42 / 71
Duality
Visualizing duality
The shortest-path problem between s and t can be solved by pulling s away
from t.
Visualizing duality
The shortest-path problem between s and t can be solved by pulling s away
from t.
Outline
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
Zero-sum games
Zero-sum games
Rock-Paper-Scissorss game. Payoff matrix (Row’s gain and Column’s loss):
Column
r p s
G= r 0 −1 1
Row
p 1 0 −1
s −1 1 0
Zero-sum games
Rock-Paper-Scissorss game. Payoff matrix (Row’s gain and Column’s loss):
Column
r p s
G= r 0 −1 1
Row
p 1 0 −1
s −1 1 0
Let’s look for a good strategy for Row.
Row plays r with probability x1 , p with probability x2 and s with
probability x3 (x = (x1 , x2 , x3 )).
Column’s strategy is y = (y1 , y2 , y3 ).
On a given round, the probability that Row plays the ith move and
Column de jth move is xi yj .
Zero-sum games
Rock-Paper-Scissorss game. Payoff matrix (Row’s gain and Column’s loss):
Column
r p s
G= r 0 −1 1
Row
p 1 0 −1
s −1 1 0
Let’s look for a good strategy for Row.
Row plays r with probability x1 , p with probability x2 and s with
probability x3 (x = (x1 , x2 , x3 )).
Column’s strategy is y = (y1 , y2 , y3 ).
On a given round, the probability that Row plays the ith move and
Column de jth move is xi yj .
The expected (average) payoff is:
X X
Gij · Prob[Row plays i, Column plays j] = Gij xi yj
i,j i,j
Zero-sum games
The expected (average) payoff is:
X X
Gij · Prob[Row plays i, Column plays j] = Gij xi yj
i,j i,j
For example, if Row plays a random strategy x = (1/2, 1/2, 0) and Column
plays r , i.e., y = (1, 0, 0), the average payoff is:
1 1 1
· 0 + · 1 + 0 · −1 =
2 2 2
Row wants to maximize this, while Column wants to minimize it.
Zero-sum games
The expected (average) payoff is:
X X
Gij · Prob[Row plays i, Column plays j] = Gij xi yj
i,j i,j
For example, if Row plays a random strategy x = (1/2, 1/2, 0) and Column
plays r , i.e., y = (1, 0, 0), the average payoff is:
1 1 1
· 0 + · 1 + 0 · −1 =
2 2 2
Row wants to maximize this, while Column wants to minimize it.
———————————————————————–
If Row plays a completely random strategy x = (1/3, 1/3, 1/3) and Column
plays any strategy y = (y1 , y2 , y3 ):
!
X X 1 X X1 X
Gij xi yj = Gij · yj = yj Gij = yj · 0 = 0
3 3
i,j i,j j i j
Zero-sum games
Zero-sum games
———————————————————————–
Zero-sum games
Nonsymmetric game:
m t
G= e 3 −1
s −2 1
Suppose Row announces that she will play the mixed strategy x = (1/2, 1/2).
What should Column do?
Zero-sum games
Nonsymmetric game:
m t
G= e 3 −1
s −2 1
Suppose Row announces that she will play the mixed strategy x = (1/2, 1/2).
What should Column do?
———————————————————————–
The best response of Column is the pure strategy y = (0, 1).
In fact, once Row’s strategy is fixed, there is always a pure strategy that is
optimal: either move m with payoff 3x1 − 2x2 , or t with payoff −x1 + x2 .
Zero-sum games
Nonsymmetric game:
m t
G= e 3 −1
s −2 1
Suppose Row announces that she will play the mixed strategy x = (1/2, 1/2).
What should Column do?
———————————————————————–
The best response of Column is the pure strategy y = (0, 1).
In fact, once Row’s strategy is fixed, there is always a pure strategy that is
optimal: either move m with payoff 3x1 − 2x2 , or t with payoff −x1 + x2 .
———————————————————————–
Row is forced to announce x before Column plays. Row knows that Column’s
best response will achieve an expected payoff of min{3x1 − 2x2 , −x1 + x2 }.
Row should choose a x that maximizes her payoff against this best response:
Pick (x1 , x2 ) that maximizes min{3x1 − 2x2 , −x1 + x2 }.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 49 / 71
Zero-sum games
Zero-sum games
Pick (x1 , x2 ) that maximizes min{3x1 − 2x2 , −x1 + x2 }.
———————————————————————–
The following are equivalent:
max z
z = min{3x1 − 2x2 , −x1 + x2 } z ≤ 3x1 − 2x2
z ≤ − x1 + x2
Zero-sum games
Pick (x1 , x2 ) that maximizes min{3x1 − 2x2 , −x1 + x2 }.
———————————————————————–
The following are equivalent:
max z
z = min{3x1 − 2x2 , −x1 + x2 } z ≤ 3x1 − 2x2
z ≤ − x1 + x2
———————————————————————–
Row must choose x1 and x2 to maximize this z:
max z
−3x1 + 2x2 + z ≤ 0
x1 − x2 + z ≤ 0
x1 + x2 = 1
x1 , x2 ≥ 0
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 50 / 71
Zero-sum games
Zero-sum games
Symmetrically, if Column has to announce his strategy first, his best bet is to
choose the mixed strategy y that minimizes his loss under Row’s best
response, in other words:
Pick (y1 , y2 ) that minimizes max{3y1 − y2 , −2y1 + y2 }.
———————————————————————–
The following are equivalent:
min w
w = max{3y1 − y2 , −2y1 + y2 } w ≥3y1 − y2
w ≥ − 2y1 + y2
Zero-sum games
Symmetrically, if Column has to announce his strategy first, his best bet is to
choose the mixed strategy y that minimizes his loss under Row’s best
response, in other words:
Pick (y1 , y2 ) that minimizes max{3y1 − y2 , −2y1 + y2 }.
———————————————————————–
The following are equivalent:
min w
w = max{3y1 − y2 , −2y1 + y2 } w ≥3y1 − y2
w ≥ − 2y1 + y2
———————————————————————–
Column must choose y1 and y2 to minimize this w:
min w
−3y1 + y2 + w ≥ 0
2y1 − y2 + w ≥ 0
y1 + y2 = 1
y1 , y2 ≥ 0
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 51 / 71
Zero-sum games
Zero-sum games
In our game the optimum is 1/7. It is realized when Row plays with optimal
strategy (3/7, 4/7) and Column with optimal strategy (2/7, 5/7).
Zero-sum games
min-max theorem
X X
max min Gij xi yj = min max Gij xi yj
x y y x
i,j i,j
Outline
1 Introduction
2 Flows in networks
3 Duality
4 Zero-sum games
max cT x
Ax ≤ b
x≥0
Assume that the origin is feasible, then it is a vertex (it is the unique
point at which the n inequalities {x1 ≥ 0, . . . , xn ≥ 0} are tight).
max cT x
Ax ≤ b
x≥0
Assume that the origin is feasible, then it is a vertex (it is the unique
point at which the n inequalities {x1 ≥ 0, . . . , xn ≥ 0} are tight).
Task 1: The origin is optimal iff all ci ≤ 0.
Simplex can be started at the origin, constraints {(4), (5)}. To move, we can
realease (5) and increase x2 gradually until it hits a constraint. It hits (3) with
x2 = 3 which becomes tight. The new vertex is given by {(4), (3)}.
yi = bi − ai · x
A potential starting vertex for this LP is: zi = bi for all i and all other variables
zero. Thus, it can be solved by simplex to obtain the optimum solution.
Jorge Júlvez (Universidad de Zaragoza) Linear Programming and Reductions 65 / 71
The simplex algorithm
A potential starting vertex for this LP is: zi = bi for all i and all other
variables zero. Thus, it can be solved by simplex to obtain the optimum
solution.
———————————————————————–
Bibliography
Bibliogaphy:
Algorithms
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani