Beruflich Dokumente
Kultur Dokumente
Principe de la méthode
Pour résoudre un problème P on procède en trois étapes :
1. Faire apparaître P comme cas particulier d’une famille de problèmes Pi ou Pij ou Pijk
2. Trouver la solution des problèmes de base
3. Trouver une formule récurrente X(i,j,k) = F(… , X(i-a, j-b, k-c), … ) pour le calcul des solutions
des problèmes de la famille
4. Construire une boucle permettant de résoudre la famille de problèmes selon la formule de
récurrence.
Commentaire
Dans la programmation dynamique pour résoudre un problème P = P(n,m,p) appartenant à une
famille de problèmes P (i,j,k), on commence par résoudre les problèmes correspondant aux plus
petites valeurs des indices i, j, k, et on conserve les solutions de ces problèmes de petites tailles dans
une table X à trois dimensions. On utilise ensuite les valeurs stockées dans la table X pour calculer les
solutions des problèmes de tailles de plus en plus grandes, jusqu’à obtenir la solution du problème
de départ P(n,m,p). On est donc amené à utiliser une boucle qui balaie la table X de sorte que si la
solution du problème de taille (i,j,k) dépend de la solution du problème de taille (i-a, j-b, k-c), alors
(i-a, j-b, k-c) est balayé avant (i, j, k).
Exemple 1
Calcul du nombre de combinaisons de q éléments parmi m : Cmq, avec m q.
Famille de problèmes : Calcul de Cnp, avec p = 0, 1, … , q (colonne) et n = p, p+1, … , m (ligne)
Cas de base : Cn0 = 1 (première colonne), Cnn = 1 (diagonale)
Récurrence : Cnp = Cn-1p-1 + Cn-1p
Calculer C75 par DPR et par programmation dynamique.
Exemple 2
Calcul de la longueur de la plus longue sous-suite commune à deux chaînes X = x1x2…xn et Y = y1y2…
ym.
Famille de problèmes : Calcul de la longueur L(i, j) de la plus longue sous-suite commune à
x1x2…xi et y1y2…yj .
Le problème initial devient le calcul de L(n,m)
Cas de base : i = 1 (première ligne), ou j = 1 (première colonne)
L(1,j) = 1 si x1 apparaît dans y1y2…yj et L(1,j) = 0 sinon
L(i,1) = 1 si y1 apparaît dans x1x2…xi et L(i,1) = 0 sinon
Récurrence : Une sous-suite de x1x2…xi et y1y2…yj peut avoir la longueur :
Cas 1 : L(i-1, j-1) + 1 si xi = yj si xi et yj sont impliqués
Cas 2 : L(i-1, j) si xi n’est pas impliqué
Cas 3 : L(i, j-1) si yj n’est pas impliqué
On a donc L(i,j) = Max L(i-1,j-1) + xi = yj, L(i-1,j), L(i,j-1)
Remarque On peut calcul cette sous-suite de longueur maximale en enregistrant le terme utilisé
pour obtenir chaque L(i,j)
Exercice : Appliquer pour ABCBDAB et BDCABA (Leiserson page 345)
Exemple 3
Déterminer si un mot w= w1w2…wn appartient au langage généré par une grammaire dont les règles
sont de la forme A a ou A BC (autrement dit si S engendre w)
Famille de problèmes : Trouver les symboles non terminaux T(i,j) qui génèrent w(i,j) =
wiwi+1…wj, avec 1 i j n.
Cas de base : 1 i = j n. Calcul de T(i,i).
Solution : Balayer les règles de la grammaire et enregistrer les symboles non terminaux A
pour lesquels il existe des règles A wi.
Récurrence. Pour calculer T(i,j), i < j,
o considérer les valeurs de k = i, i+1, … , j-1
o T(i,j) correspond aux symboles A qui engendrent BC, et tels que B engendre wi…wk et
C engendre wk+1 … wj, autrement dit B T(i,k) et C T(k+1,j).
Complexité O(n3) à cause des trois boucles imbriquées sur i, j et k.
La réponse à la question de départ est positive si l’axiome S est dans T(1,n).
Exemple 4
Expression régulière correspondant au langage reconnu par un automate fini A = (, Q, q0, F, )
Exemple 5
Plus courts chemins entre tous les sommets d’un graphe
Exemple 6
Retour de monnaie (cf Poly Montréal)
Exemple 7
Problème du sac à dos (cf Poly Montréal)
Exemple 8
Minimisation du nombre d’opérations lors de la multiplication chaînée de matrices
Exemple 9
Arbre binaire de recherche optimal
Exemple 10
Partition optimale d’un nombre
Exemple 11
Ordonnancement optimal d’une chaîne de montage
Exemple 12
Traversée d’une pyramide de nombres
En partant du sommet, et en se dirigeant vers le bas à chaque étape, on veut maximiser le total des
nombres traversés. Sur l'image d'exemple, ce maximum est 23 (le chemin est indiqué en rouge).
Montrer que le nombre total de chemins est exponentiel = 12 + 22 + … + 2h, pour une
pyramide de h niveaux.
Solution : A la racine (niveau 1) on a 1 sommet et 1 chemin. Au niveau 2 on a 2
sommets et 1 + 1 chemins. A un niveau h > 2, on a h sommets avec 1, x2, … , xh-1, 1
chemins, donc au total 1+ x2 + … + xh-1 + 1 chemins. Au niveau h+1 > 3, on a h+1
sommets avec au total 1+ y2 + … + xh + 1 chemins, et
yi = xi-1 + xi.
1
1 1
1 2 1
1 3 3 1
Exemple 13
Alignement de séquences (Wikipedia)
Exemple 14
Distance de Levenshtein
http://people.cs.clemson.edu/~bcdean/dp_practice/
To view the solution to one of the problems below, click on its title. To view the solutions, you'll need a machine which can
view Macromedia Flash animations and which has audio output. I have also included a short review animation on how to solve
the integer knapsack problem (with multiple copies of items allowed) using dynamic programming.
Problems:
1. Maximum Value Contiguous Subsequence. Given a sequence of n real numbers A(1) ... A(n),
determine a contiguous subsequence A(i) ... A(j) for which the sum of elements in the
subsequence is maximized.
2. Making Change. You are given n types of coin denominations of values v(1) < v(2) < ... < v(n)
(all integers). Assume v(1) = 1, so you can always make change for any amount of money C.
Give an algorithm which makes change for an amount of money C with as few coins as
possible. [on problem set 4]
3. Longest Increasing Subsequence. Given a sequence of n real numbers A(1) ... A(n), determine
a subsequence (not necessarily contiguous) of maximum length in which the values in the
subsequence form a strictly increasing sequence. [on problem set 4]
4. Box Stacking. You are given a set of n types of rectangular 3-D boxes, where the i^th box has
height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes
which is as tall as possible, but you can only stack a box on top of another box if the
dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base
of the higher box. Of course, you can rotate a box so that any side functions as its base. It is
also allowable to use multiple instances of the same type of box.
5. Building Bridges. Consider a 2-D map with a horizontal river passing through its center.
There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the
northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south
pairs of cities as possible with bridges such that no two bridges cross. When connecting cities,
you can only connect city i on the northern bank to city i on the southern bank. (Note: this
problem was incorrectly stated on the paper copies of the handout given in recitation.)
6. Integer Knapsack Problem (Duplicate Items Forbidden). This is the same problem as the
example above, except here it is forbidden to use more than one instance of each type of item.
7. Balanced Partition. You have a set of n integers each in the (cf Poly Montréal) range 0 ... K.
Partition these integers into two subsets such that you minimize |S1 - S2|, where S1 and S2
denote the sums of the elements in each of the two subsets.
8. Edit Distance. Given two text strings A of length n and B of length m, you want to transform A
into B with a minimum number of operations of the following types: delete a character from
A, insert a character into A, or change some character in A into a new character. The minimal
number of such operations required to transform A into B is called the edit distance between
A and B.
9. Counting Boolean Parenthesizations. You are given a boolean expression consisting of a string
of the symbols 'true', 'false', 'and', 'or', and 'xor'. Count the number of ways to parenthesize
the expression such that it will evaluate to true. For example, there are 2 ways to
parenthesize 'true and false xor true' such that it evaluates to true.
10. Optimal Strategy for a Game. Consider a row of n coins of values v(1) ... v(n), where n is even.
We play a game against an opponent by alternating turns. In each turn, a player selects either
the first or last coin from the row, removes it from the row permanently, and receives the
value of the coin. Determine the maximum possible amount of money we can definitely win if
we move first.
11. Maximum Value Contiguous Subsequence. Given a sequence of n real numbers A(1) ... A(n),
determine a contiguous subsequence A(i) ... A(j) for which the sum of elements in the
subsequence is maximized. http://people.csail.mit.edu/bdean/6.046/dp/
Exams : http://cgi.cse.unsw.edu.au/~cs3121/Assign/Midterm-Practice.pdf