Algorithms and Data Structures
Algorithms and Data Structures
Algorithms and Data Structures
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 121<br />
2. There might be a man pm, preferred to m by w, who himself prefers w over his wife.<br />
Pursuing trouble source 1, we compare ranks rwm pw,m <strong>and</strong> rwm pw,y[pw] for all women preferred to m<br />
by w, i.e. for all pw = wmr m,i such that i < r. We happen to know that all these c<strong>and</strong>idate women are<br />
already married because, were anyone of them still single, m would have picked her beforeh<strong>and</strong>. The<br />
described process can be formulated by a simple linear search; S denotes stability.<br />
i := -1; S := TRUE;<br />
REPEAT<br />
INC(i);<br />
IF i < r THEN<br />
pw := wmr[m,i];<br />
IF ~single[pw] THEN S := rwm[pw,m] > rwm[pw, y[pw]] END<br />
END<br />
UNTIL (i = r) OR ~S<br />
Hunting for trouble source 2, we must investigate all c<strong>and</strong>idates pm who are preferred by w to their<br />
current assignation m, i.e., all preferred men pm = mwr w,i such that i < rwm w,m . In analogy to tracing<br />
trouble source 1, comparison between ranks rmwp m,w <strong>and</strong> rmw pm,x[pm] is necessary. We must be<br />
careful, however, to omit comparisons involving x pm where pm is still single. The necessary safeguard is a<br />
test pm < m, since we know that all men preceding mare already married.<br />
The complete algorithm is shown below. Table 3.4 specifies the nine computed stable solutions from<br />
input data wmr <strong>and</strong> mwr given in Table 3.3.<br />
PROCEDURE write; (* ADenS36_Marriages *)<br />
(*global writer W*)<br />
VAR m: man; rm, rw: INTEGER;<br />
BEGIN<br />
rm := 0; rw := 0;<br />
FOR m := 0 TO n-1 DO<br />
Texts.WriteInt(W, x[m], 4);<br />
rm := rmw[m, x[m]] + rm; rw := rwm[x[m], m] + rw<br />
END;<br />
Texts.WriteInt(W, rm, 8); Texts.WriteInt(W, rw, 4); Texts.WriteLn(W)<br />
END write;<br />
PROCEDURE stable (m, w, r: INTEGER): BOOLEAN;<br />
VAR pm, pw, rank, i, lim: INTEGER;<br />
S: BOOLEAN;<br />
BEGIN<br />
i := -1; S := TRUE;<br />
REPEAT<br />
INC(i);<br />
IF i < r THEN<br />
pw := wmr[m,i];<br />
IF ~single[pw] THEN S := rwm[pw,m] > rwm[pw, y[pw]] END<br />
END<br />
UNTIL (i = r) OR ~S;<br />
i := -1; lim := rwm[w,m];<br />
REPEAT<br />
INC(i);<br />
IF i < lim THEN