You are on page 1of 134

Programozói versenyfeladatok,

alapvető matematikai algoritmusok

Kiss Csaba Zsolt


Programtervező matematikus
KLTE
Debrecen

1994.
Tartalomjegyzék

Bevezetés 2
A versenyekről. 3
1. Kombinatorikai algoritmusok 6
1.1. Ismétlés nélküli permutációk. 6
1.2. Ismétléses permutációk 10
1.3. Kombinációk 13
1.4. Egy halmaz összes részhalmazai, particionálása 16
1.5. Gray kódok 23
2. Geometriai algoritmusok 26
Bevezetés 26
2.1. Szakaszok metszete 28
2.2. Poligon és pont 31
2.3. Ponthalmaz konvex burka 34
3. Gráfalgoritmusok 39
Bevezetés 39
3.1. Mélységi keresés 40
3.2. Optimális keresés 44
Függelék 52
Ábrák, programok listája 52
Problémák listája 52

1
Bevezetés

A dolgozat címében hivatkozott versenyfeladatok az ACM szervezésében rendezett egyetemi


programozói csapatversenyek feladatai. A versenysorozatot évente rendezik és három fordulóból áll.
Az első forduló általában valamilyen helyi (egyetemi, városi) verseny. Ezeket a versenyeket a helyi
(lelkes) szervezők szervezik, általában önkéntes alapon. Szervezésen itt a verseny tényleges
lebonyolítását kell érteni és a feladatok kiválasztását. A helyi versenyekről tovább jutó csapatok
vesznek részt a második fordulóban (egyetemenként legfeljebb egy csapat), amelyet már az ACM
adott szervezete szervez. A második fordulóban (Regional Final - területi döntő) általában valamilyen
nagyobb területi egység (Pl. Kalifornia, Nyugat-Európa) egyetemeinek csapatai versenyeznek. A
területi döntőkből egy-három csapat juthat tovább a döntőbe, amely mindig valamelyik USA-beli
nagyvárosban zajlik.
A dolgozatom célja a verseny és a verseny feladatainak általános bemutatása. Egyetemi éveim alatt
összesen 7 -szer vettem részt 1. és 2. fordulós versenyeken. Az itt összegyüjtött tapasztalatokat és
szép megoldásokat, a megoldásokhoz felhasmált alapvető matematikai algoritmusokat úgy éreztem
mindenképpen szükséges rendszerezve megörökíteni, ehhez kínált kiváló fórumot a diploma
dolgozatom.
A dolgozat melléklete kb. 90 eredeti versenyfeladatot tartalmaz, amely biztosan nagyon hasznos lesz
az egyetemünkön folyó első és másod éves programozó-matematikus, matematikus, informatika és
matematika tanár szakos hallgatók különböző tantárgyainak gyakorlati oktatásához. . A feladatok
angol nyelvűek, mert a versenyek hivatalos nyelve az angol.
A dolgozatban található alapvető matematikai algoritmusok segítségével mintegy 30 (általában a
nehezebbek közé sorolt probléma) oldható meg. Az algoritmusok kisebb módosításaival további
feladatok megoldhatók. Az egyes algoritmusoknál hivatkozás található a feladatokra, amelyek
megoldásához az adott algoritmus jó hatásfokkal felhasználható. Az egyes algoritmusok újabb
problémákat vetnek fel (P-jelű problémák) ezek megoldása szintén jó gyakorlat lehet.
Ezúton szeretnék a csapatom nevében köszönetet mondani szakmai támogatóínknak és tanárainknak
akik nélkül még az így elért szerény eredményeinket sem értük volna el, név szerint: Kuki Attilának a
helyi versenyek szervezéséért és az európai döntőre való kiutazás szervezéséért, valamint hasznos
tanácsaiért, Dr Arató Mátyásnak, Dr Lajkó Károlynak, Dr. Juhász Istvánnak és Dr Végső Jánosnak
általános támogatásaikért, Herendi Tamásnak igen hasznos szakmai tanácsaiért és az IFSz Kft.
valamint az IQSoft Rt. munkatársainak szakmai és egyéb támogatásukért. Végül szeretnénk
megköszönni anyagi támogatásukat azon cégeknek és szervezeteknek akik nélkül semmiképpen sem
képviselhettük volna egyetemünket az európai döntőkön:

A Külkereskedelmi és Hitel Bank Rt.,


A Biogal Rt.,
Az IQSoft Rt.,
A Dataware Kft.,
A KL TE Diákönkormányzata.

Valamint szeretném megköszönni csapattársaimnak Fekete Zoltánnak, Jakó Jánosnak,


Molnár Tamásnak és tanáraimnak Kuki Attilának és Herendi Tamásnak a dolgozat elkészüléséhez
adott hasznos tanácsaikat és bölcs észrevételeiket.

2
A versenyekről

A verseny szabályai:

A versenyeken kezdetben 4, majd (1991 után) 3 fós csapatok indulhattak. A csapat tagjai között
kezdetben lehetett egy diplomás is, később diplomások részvétele nem volt megengedett. A verseny
ideje általában 5 óra. A csapatok a verseny ideje alatt egy darab IBM PC típusú számítógépet
használhatnak a szükséges fordítóprogrammal felszerelve, ez a TURBO PASCAL 5.0 -ás verziója
volt. A csapatok a verseny alatt bármilyen írott forrást használhatnak, viszont semmilyen más (pl.
mágneses) forrás használata nem megengedett csakúgy, mint a programozható zsebszámológépek
használata sem. A csapatoknak a verseny ideje alatt 5-8 problémát kell megoldaniuk. A problémák
között semmilyen sorrendiség sincs. A verseny nyelve angol, ezért a feladatok szövege, a zsűrinek
feltett kérdések, a zsűri válaszai is angol nyelvűek.

A problémák megoldása

A csapatoknak az elkészült megoldást -amely mindig egy pascal program forráskódja - az e célra
fenntartott mágneslemezen kell a zsűrihez eljuttatniuk. A zsűri a kódot lefordít ja és saját input
adataival teszteli. A programoknak 1 perc futásidő áll rendelkezésére, ez alatt kell outputot
produkálniuk. Az output alapján a zsűri a következő válaszokat adhatja a csapatoknak:

1. Syntax Error - fordítási hiba


2. Run Time Error - Futás közbeni programhiba, pl O-val való osztás
3. Time Limit Exceded - Időtúllépés
4. Wrong Answer - hibás válasz.
5. Accepted - Elfogadva

Egy probléma megoldásával többször is lehet próbálkozni, de zsűri csapatonként és problémánként


méri a verseny kezdetétől a megoldáshoz felhasznált időt. Az 1.-4. esetben (és minden további
sikertelen kísérlet után) a zsűri az adott csapatnak adott probléma megoldásához felhasznált idejét 20
perccel növeli.
A verseny ideje alatt az egyes feladatokkal kapcsolatban felmerült értelmezési stb. problémákkal
kapcsolatban a csapatok írásban kérdéseket tehetnek fel a zsűrinek, aki szintén írásban köteles
válaszolni ezekre. A zsűri a csapatokat szabályszegés esetén kizárással sújthatja.

A Kiértékelés szabályai:

A verseny végeztével a zsűri összeszámolja az egyes csapatok által megoldott problémák számát, és
összeadja a helyesen megoldott problémákhoz felhasznált időket. Így minden csapat eredménye két
mennyiségből áll:
- A megoldott problémák száma
- Az ehhez felhasznált idő

Az a csapat a verseny győztese, amely a legtöbb feladatot oldotta meg, ha ilyen több van akkor a
verseny győztese az a csapat, amely a legkevesebb időt használta fel.

Hazai Versenyek

Az egyetemi programozói versenyek története Magyarországon 1990-ben kezdődött egy a Budapesti


Műszaki Egyetemen (BME) rendezett versennyel, ahol nemcsak a BME csapatai, hanem a fóvárosi
egyetemeken kívül vidéki csapatok is indultak. Ezen a versenyen a KL TE 3 csapatot indított, melyek
a középmezőnyben végeztek. 1991 után minden évben a fóvárosban és Debrecenben is rendeztek
versenyeket. Ezeken a versenyeken az induló csapatok száma nagyjából állandó volt: Budapesten kb
25, míg Debrecenben kb 10.

3
A versenyek tapasztalatai

A következő néhány mondatban a versenyeken, a problémák megoldásával kapcsolatban szerzett


tapasztalatokról szeretnék írni. A verseny kezdetén érdemes minden feladatot átolvasni és értelmezni.
Az egyes csapatokon belül többféle megoldási módszer is kialakulhatott, az egyik lehetséges, hogy az
értelmezés után a csapattagok egymás között szétosztják a feladatokat és eztán egyenként, vagy
problémás feladat esetén együtt keresik a megoldást és valósítják meg a kivitelezést. A másik
módszer, hogy minden feladat elvi megoldását a csapattagok együtt keresik, csak a konkrét
megvalósítás ideje alatt dolgoznak különböző feladatokon a csapattagok. De ezektől különböző más
módszerek is kialakulhattak, valószínűleg erre nincs általános alkalmazható stratégia. A feladatok
megoldásakor szerenesés esetben, amikor egyszerre több feladat elvi megoldása is elkészült, a szűk
keresztmetszetet a rendelkezésre álló egyetlen számítógép gépideje (5 óra) jelenti. Érdemes a
legkönnyebb, legegyszerűbb probléma megoldásának megvalósításával kezdeni. A megoldásokban
nem kell szépségre és az eleganci ára törekedni, mert a zsűri ezt nem értékeli. Sokkal inkább a kód
egyszerűségére és átláthatósága kell, hogy a cél legyen. A feladatok elég nagy része többféleképpen is
megoldható. Azoknál a feladatoknál, ahol a megoldást el lehet érni a feladatbeli objektumok összes
esetének (pl. összes permutáció) vizsgálatával, ott a program rendelkezésére álló 1 perces futási időre
kell figyelnünk, azaz tisztában kell lennünk az átlagos PC-k (különösen a zsűri által használt PC) .:»
gyorsaságával. Viszont ha az összes eset vizsgálata belefér az egy perces futási időbe, nem érdemes a
szép és "eszes" megoldás megkeresésévei foglalkozni. A későbbiekben az adott helyen az egyes
algoritmusok futási idejére utalni fogunk.

A mellékletben található feladatok

A mellékletben található feladatokra a dolgozatban a feladatok azonosítójával hivatkozunk, amely


XXXXéé-n alakú, ahol XXXX a verseny helyszínének rövidítése, éé a verseny megrendezésének
évszáma évszázad nélkül, n pedig a feladat sorszáma. A mellékletben a feladatok évszám szerint
növekvő sorrendben találhatók. A formátumuk eltér az eredetitől, hogy egységesen kezelhessük őket.
A legnagyobb része a feladatoknak négy jól körbehatárolható csoportból kerül ki. Ezek a
következőek:

1. Szimulációs feladatok
Ezekben a feladatokban jól definiált objektumokkal találkozhatunk, amelyekhez szabályok tartoznak.
Az objektumok ezen szabályok szerint viselkednek. A megoldáshoz nem kell egyéb, mint a feladat
pontos megértése, az objektumok megfelelő gépi reprezentál ása és a szabályok pontos programozása.

Könnyebb szimulációs problémák: USSC85-3, KLTE91-1, RUGB91-1, RUGB91-2,


ACMF91-5, IOAG91-1, ODUN92-1, RUGB92-2, RUGB92-5, KLTE92-2, USEC92-
2, ACMF92-1, KLTE93-4

Nehezebb szimulációs problémák:KLTE91-2, RUGB91-5, RUGB91-7, ACMF91-3,


ACMF91- 4, RUGB92 -6, TUBP92-1,

A szimulációs feladatok megoldásával a dolgozatban nem foglalkozunk. Megoldásukat a Pascal


nyelvvel ismerkedőknek ajánlhatjuk. Megoldásukhoz csak alapvető matematikai ismeretekre van
szükség.

2. Kombinatorikai feladatok
lásd a dolgozat első fejezetét

3. Geometriai feladatok
lásd a dolgozat második fejezetét

4. Gráfelméleti problémák
lásd a dolgozat harmadik fejezetét.

4
Az egyes versenyek helyszínei és időpont ja:

Rövidítés Színt Helyszín Időpont


(forduló)
USSC85 2 ?, California , USA 1985.
KLTE91 1 KL TE, Debrecen 1991. Június
IOAG91 * Athen, 3rd International 1991. Május
Olympiad in Informatics
TUBP91 1 BME, Budapest 1991. Október
RUGB91 2 Gent, Belgium 1991. November
ACMF91 3 USA 1991.
USSC92 2 ?, USA 1992.
ODUN92 1 Norfolk, Va USA 1992. Szeptember
TUBP92 1 BME, Budapest 1992. Október
KLTE92 1 KL TE Debrecen 1992. Október
RUGB92 2 Gent, Belgium 1992. November
ACMF92 3 Indíanapolis, USA 1992.
KLTE93 1 KL TE, Debrecen 1993. Szeptember

5
1. Kombinatorikai algoritmusok

1.1. Ismétlés nélküli permutációk

Vizsgáljuk először az ismétlés nélküli permutációk generálásának problémakörét. A probléma pontos


defmíciója a következő:

Adott a P={ 1,2 ..n} halmaz, előállítandó

a) az összes permutációja tetszőleges sorrendben.


b) az összes permutáció ja lexikografikus sorrendben.
c) a lexikografikus rendezés szerinti i-edik permutációja

A P összes permutációinak halmazát jelöljük P! -al : P! = {~, pz 'o 00' Pn! }


Először az egyik legegyszerubb módszer bemutatásával kezdjük. A módszert Fike publikálta 1975-
ben [Fike1975] , majd 1976-ban Rohl módosította [Roh1l976] .
Legyen S={(d2,d3, ••• ,dn) II~dk s k: k=2,3, .. n} ekkor S összesen 2*3* ..*n=n! vektort
tartalmaz. Vegyük észre, hogy S elemeit programmal könnyen lehet generálni: kis n esetén n-l darab
egymásba ágyazott ciklussal, ahol a ciklusváltozók értékei rendre az [1..2], [1..3], ... ,[1..n]
intervallumokat futják be, nagy n esetén rekurzívan. Ha egyszeruen programozható egy-egy értelmű
megfeleltetést adnánk S és P! elemei között akkor, mivel S elemeit könnyen generálhatjuk egyszeru
módszert kapnánk P! generálására. A Fike módszere a következő egy-egy értelmű megfeleltetést adja
S és P! elemei között: Legyen (d2, d3, ••• , dn) egyelem S-ből, ekkor a hozzátartozó P permutációt
úgy kapjuk, hogy kiindulva ~ = (1,2, ... , n) - ből, mint kezdeti permutációból cseréljük fel P; -ben a
k-adik elemet a dk -adikkal.
Mindezek alapján az algoritmus először az S-beli elemeket generálja, majd ebből állítja elő a fent
leírtaknak megfelelően a kapcsolódó permutációt.
Észrevehető, hogy a fenti algoritmus redundáns elemeket tartalmaz (pl ha dk = k, akkor felesleges
csere), ezen elemek kiküszöbölésére tett módosítást 1976-ban J. S. Rohl. A Rohl által módosított
algoritmus pascal programja a következő:

proeedure Fike_Rohl_perm(n:integer);
var p:array[l ..max) of integer; { n <= max}
i:integer;
proeedure permute(k:integer);
var temp, dk, dn:integer;
begin
if k=n then begin
proe (p) ;
temp: =p [nl ;
for dn:=n-l downto 1 do
begin
p[n) :=p[dn) r p l dn ) :=temp;
p.roc t p j r
p j dn l r=p I n l r
end;
p[n) :=temp;
end
else begin
permute (k+l) ;
temp :=p [k) ;
for dk:=k-l downto 1 do
begin
p [k) :=p [dk) ;

6
p[dk] :=tempi
permute(k+l)i
p [dk] :=p [k] i
e rid r
p[k] :=tempi
endi
endi
be gin {Fike_Rohl perm}
for i:=l to n do p[i] :=ii
permute(2)i
endi

Fig. 1.1.1..' Fike algoritmusa Rohl módosításaival

A versenyfeladatok megoldásánál a közölt eljárás általában jól használható, de azokban a


problémákban ahol a feladat szempontjából n állandó és n nem túl nagy (n<6), elképzelhető olyan
eljárás is amely n darab egymásba ágyazott ciklust tartalmaz az S elemeinek generálásához. Ennek
az algoritmusnak a gyorsaság mellett a kód egyszerűsége is az előnye.
A fenti módszer csupán az (a) problémára ad választ. Ha pl. valamely feladat a lexikografikus
sorrendben követeli meg tőlünk a permutációk felsorolását, akkor a módszerek egy újabb családjával
kell megismerkednünk [We1ll971] . Most egy olyan módszert mutatunk be, amely 1812-ből
származik, első említése [FiscI812] majd [ShenI962] . A módszer lényege négy lépés alkalmazása
=
egy adott P (Pl' P2'''' Pn) permutációra, amely eredményeként a lexikografikusan következö
permutációt kapjuk

A négy lépés:

(1) Legyen i a legnagyobb index, amelyre p i-l< Pi


(2) Legyen} az a legnagyobb index, amelyre Pi-I<Pj
(3) Cseréljük fel Pi-l -et p.-vel.
(4) Fordítsuk meg Pl' Pi+I,··.,Pnsorrendjét.

Fig. 1.1.2 ..'A lexikografikus felsorolás négy lépése

Pl. 1.1. Írjunk olyan pascal programot, amely az 1.1.2 ábra alapján lexikografikus sorrendben
generálja egy halmaz partícióit

Most egy másik, a permutációkat lexikografikusan felsoroló módszer mutatunk be. P! egy általános
elemének generálásakor az összes N={l,2 ..n} számnak hozzá kell rendelődnie a Pl -hez, majd az
N \ {Pl} -beli összes elemnek hozzá kell rendelődnie a P2-höz, és így tovább. Ezek alapján
algoritmusunk szerkezete a következő: Ahhoz, hogy a permutációkat lexikografikus sorrendben
kapjuk korlátoznunk kell az egyes Pj -k kiválasztásának sorrendjét. Ha a választható elemek közül
elsőként mindig a kisebbiket választ juk, akkor a permutációkat lexikografikusan növekvő sorrendben
kapjuk.
Kézenfekvő, hogy algoritmusunkban a választható elemeket egy listában tároljuk, a listák kezelése
(elem-törlés, -beszúrás, stb.) a pascal nyelvben a jól ismert mutatós módszerrel talán túl sok
adminisztrációs lépéssei járna, ezért kihasználva a jelen probléma specifikurnát a megfelelő listát egy
tömbbel szimuláljuk, legyen ez a:array[O ..n} o/integer. A tömb egy elemének indexe reprezentálja
i-edik listaelem által tárolt értéket, míg maga az elem a lista következő elemére mutat. Vagyis pl. az
[1,3,3,4,6,6,0] tömb az 1 ~ 3 ~ 4 ~ 6 listát reprezentálja.

7
Ekkor az a[O..n] inicializálását, feltöltését a következő eljárás végzi:

procedure Init;
var i: integer;
begin
for i:=O to n-l do a[i):=i+l;
a[n):=O;
end;

Tegyük fel, hogy p[1..n] egy globális tömb var p:array[1 ..n} of integer defmícióval, a permutációk
tárolásához, valamint már létezik a PrintPerm eljárás a kész permutációk megjelenítéséhez. Ekkor a
permutációkat lexikografikusan felsoroló algoritmus pascal kódja a következő:

procedure enum(i:integer);
var t:integer;
begin
t:=Oi
while a[t)<> O do
begin
p[i]:=a[t];
if i<> n
then
begin
a [t] :=a [a [t]];
enum(i+l) ;
a [t] : =p [i] ;
end
else
Printperm;
t:=a[t];
end;

Fig. J. J. 3.: Permutációk lexikografikusan

Az algoritmusunknál alkalmazott gondolatmenet, mint majd látni fogjuk ismétléses permutációkra is


általánosítható lesz.
A fenti algoritmusok teljesítménye között a versenyfeladatok megoldásának szempontjából lényeges
különbség nincs. Ezen azt kell érteni, hogy a megoldások a futásra felhasználható idő (1 perc) alatt
nagyjából n=ll-ig képesek az összes permutációt előállítani. Természetesen a fenti módszereken
kívül számos más módszer is ismeretes, melyek más-más célra használhatók a legalkalmasabban. A
különböző algoritmusok több szempontú összehasonlításával foglalkozik Roy [RoyI978] és Ives
[Ivesl976].
A probléma (c) részében megfogalmazottakra mind Fike [FikeI975], mind Wells [WeIIsi971] kínál
megoldást. A (c)-ben megfogalmazott probléma speciális esete (n=k) annak a problémának amikor
egy n elemű halmaz k-ad osztályú kombinációinak összes permutációit rendezzük lexikografikusan és
ezek között keressük a i-ediket. Ennek az általánosabb problémának a megoldása a "Kombinációk"
című fejezetben található.
A (c) problémára ezen kívül hasznos eligazítást találhatunk [BrowI970] -ban is.

Irodalomjegyzék az 1.1. fejezethez

[FikeI975]: C. T. Fike (1975). A permutation generation method. The Computer Journal, Vol.
18,p21.
[Rohll976]: 1. S. Rohl (1976). Programming improvements to Fike's algorithm for generating
permutations. The Computer Journal, Vol. 19, p 156.

8
[WeIll 1971]: M. B. Wells (1971). Elements ofCombinatorial Computing. Pergamon Press,
NewYork
[Fisc1912]: L. L. Fischer and K. Chr Krause (1812). Lehrbuch der Combinationslehre und der
Arithmetik. Dresden.
[Shen1962]: Shen, Mok-Kong (1962). BIT Vol. 2. p. 228.
[RoyI978]: M. K. Roy. (1978). The Computer Journal, VoI2l., p. 296.
[Ivesl976]: F. M. Ives. (1976).Permutation Enumeration: Four New Permutation Algorithms
CACM, Vol. 19., Nr. 2., p. 68.
[Brow 1970]: R. M. Brown: Decoding Combinations of the First n Integers Taken k at a Time.
CACM Vol. 3-4 p 235.

9
1.2. Ismétléses permutációk

A probléma pontos definíciója a következő:


Adott 1 <= r <= n pozitív egész (n darab, r különböző elem permutációit keressük),
r

valamint azF = (ft .t; ···,fr') vektor, ahol n = LJ; és 1::;; J; (i = 1,2, ... r)
;=1

generálandó az M = {u,..,1,2,2, .. ,2, .... ,r,r, .. ,r}


~ ~ '---v---'
ft h /,
halmaz összes (ismétléses) permutációja.
Egy ilyen permutációt jelöljünk csakúgy, mint az előzőekben P = (Pl' P2"" Pn) -vel.
A P-t generáló algoritmusunk egybeesik azzal a módszerrel ahogyan "kézzel" felírnánk a fenti
permutációkat: Válasszunk M-ből egy elemet az összes lehetséges módon ez lesz Pl' minden egyes
ilyen választás után válasszunk egy elemet M\{Pl}-ből P2-helyére, ..., és végül minden egyes Pn-l
kiválasztása után Pn helyére válasszunk M \ {Pl' P2"'" Pn-l} -ből, mint az előző fejezetben. Ha r=n
akkor az ismétlés nélküli permutációkat kapjuk. Ha az 'összes lehetséges módon' történő választást
az elemek növekvő sorrendjében végezzük el, akkor a permutációkat is lexikografikusan ebben a
sorrendben kapjuk. Rohl 1978-ban publikálta [Roh1l978] a fenti módszert némi általánosítással: Ha
az algoritmus során a kiválasztásokat nem végezzük el csak Ps -ig (S < n )-ig akkor n-elem s-ed
osztályú kombinációinak (ismétléses) permutációit (s-permutációit) kapjuk csakúgy, mint az előző
fejezetben.
Végül algoritmusunk programja a következő:

procedure genperm(m,f:vect;r,rO:integer);
const max=20;
type vect=array[l ..max] of integer;

var
p:intvect;
k:integer;

procedure choose(k:integer);
var
i:integer;
begin
for i:=l to r do
if f[i] <> O then
begin
p [k] : =m [i] ;
dec(f[i]);
if k<>rO then choose(k+l) else proc(p);
inc(f[i]);
end
end;

begin {genperm}
choose(l);
end;

Fig. 1.2.1.: Rohl algoritmusa (1978).

10
Ha valamely n elem ismétléses permutációi közül a lexikografikus sorrendben pontosan az i. -re van
sziikségünk akkor az ezt előállító algoritmust Wells [Welli971] munkájában találjuk. Készítsük most
el az i-edik lexikografikus ismétléses permutációt generáló algoritmus saját verzióját. Kiindulásként
alkalmazzuk Wells az "inverzfeladat"-ot megoldó algoritmusát [We1ll971] . Ez az algoritmus az
inputjaként egy permutációból előállítja az adott permutáció lexikografikus sorrendbeli sorszámát:

const max=100i
type intvect=array[O ..max] of longinti

function nalatt k (n:longintik:longint) :longinti


Var
i :integer i
result:longinti
Begin
result:=li
if k<>O then
for i:=O to (k-1) do result:=(result div (i+1) )*(n-i)i
nalatt k:=result
endi

function iperm2num(n,r:integerif,p:intvect) :longinti


(* osszesen k-1 fele objektumunk van,
osszesen n darab objektumunk van,
n=f [O]+f [1]+ ...+f [r-1]
f[j]: a j. objektumból f[j] darab van O <= j <= r-1
*)

var
H,MM,J:intvecti
q,i,jj:integeri
nn,v:longinti
begin
for i:=O to r-1 do begin h[i] :=OiMM[i] :=Oij[i] :=1 endi
for i:=O to n-1 do
begin
MM[p[i]] :=MM[p[i] ]+n_alatt k(h[p[i]],j [p[i]]) i
inc(h[p[i]]) iinc(j [p[i]]) i
for q:=O to p[i]-l do inc(h[q])i
e nd r
v:=liNN:=Oiq:=f[r-1]i
for jj:=r-2 downto O do
begin
NN:=NN+MM[jj]*Vi
q:=q+f[jj];
v:=v * n_alatt k(q,f[jj]);
end;
iperm2num:=NN
endi

Fig. 1.2.2.: Wellsféle JPERM2NUM foggvény (1971).

II
A mi feladatunk azonban olyan algoritmus írása, amely a sorszám alapján "legyártja" a hozzá
tartozó (ismétléses) permutációt.
Vegyük észre, hogy adott M és resetén M bármely MO részhalmazának a lexikografikusan első
(jelöljük [MO]F-al) ill. lexikografikusan utolsó permutációja (jelöljük [MO]L-el) egyszeruen
megadható az elemek sorbarendezésével.
Keressük tehát a M lexikografikusan K-adik permutációját P-t. Próbáljuk megkeresni Pl-et P első
betűjét, ekkor PI-re:

ipemünumcn -1, r', f', [{M\PI }]L ) =< K,

ahol f ,[;]
. ..= {fU] . - 1, ha j = Pl
"
.
,(; = 1,2, ...r) (1)
f[;], egyébként

r' := {r -1, ha f[PI] =1


r , egyébkén!

és nyilván Pl az a szimbólum amelyre iperm2num(n-l,r', f', [{M\PI}]L) maximális (1)


tulajdonságú.
Pl után P2-t mint n-1 darab és r' különböző szimbólum lexikografikus sorrendben vett
K - perm2num(n -1, r', f', {M\ Pl}) sorszámú permutációjának első betűjeként keressük ..
és így tovább egészen Pn-ig. Legyen az ezt megvalósító pascal kód megírása ismét az olvasó feladata!

P 1.2.1. Írjunk olyan pascal függvényt, amely az előzőek alapján generálja a K. sorszámhoz tartozó
lexikografikus permutációját valamely M halmaznak !

Valamely halmaz ismétléses permutációit előállító algoritmust találunk még [Barti967] -ben és
[SagI964]-ben is.

Kapcsolódó versenyfeladatok:

Feladat Instrukció

UUSC85-2 Az összes esetek száma (kb. 9!) lehetővé teszi, hogy egyenként megvizsgáljuk őket
A megadott öt szám összes permutációit (5!) vizsgáljuk, az összes lehetséges
müveletjelezéssel (44).
TUBP91-4 Az egyenlő számjegyek elhagyása után az összes esetek száma 10!
RUGB92-1 Ismétléses permutációk lexikografikusan
RUGB92-4 Mivel a gráf csúcsainak száma nem több mint 8, ezért a csúcsok összes lehetséges
sorrendjét megvizsgálva (8!) a minimálisat bizonyosan megtaláljuk
ACMF92-2 A hálózatba kapcsolt gépek maximális száma 8, ezért az összes eset vizsgálata
KLTE93-3 lehetséges.

Irodalomjegyzék az 1.2 fejezethez

[Rohll978]: J. S. Rohl. (1978). Generating permutations by choosing. The Computer Journal,


Vol 21., p 303.
[we1ll971 ]: M. B. Wells (1971). Elements ofCombinatorial Computing. Pergamon Press, New
York
[Bratl967]: P. Bratley (1967).Permutations with repetitions. CACM Vol. 10. p. 450
[Sag1964]: T. W. Sag (1964) Permutations of set with repetitions. CACM Vol. 7. p 585.

12
1.3. Kombinációk

Ebben a fejezetben a feladatunk n-elem r-edosztályú ismétlés nélküli kombinációinak generálása,


úgy, a generált kombinációk sorrendje is számít. Ahogy már az ismétlés nélküli permutációkkal
foglalkozó fejezetben utaltunk rá, ez a probléma az ismétlés nélküli permutáció generálás
általánosításának tekinthető.
Most az előző fejezetekkel ellentétben csak a legáltalánosabb eljárást mutatjuk be. Nem foglalkozunk
a "rendezettlen" kombinációk generálásával. A lexikografikus algoritmusok közül is csak azzal
foglalkozunk, amely a lexikografikusan t. kombinációt fogja közvetlenül előállítani.
Keressük praktikusan a Z; = {l, 2, .... , n} halmaz r-edosztályú kombinációinak összes permutációit,
vagyis a Pn.r = Pl>P2"'"
Pr ,ahol Pl>P2'" .,Pr E {l, 2, ... ,nl és Pi :j:; P, ha i :j:; j. vektorokat.
Ezek halmazát jelöljük P(n, r)-el. Nevezzük Pn. r = Pl> P2'"'' Pr -t a rövidség kedvéért el egy r-
permutációnak !

Legyen P; r = Pl' P2"'" Pr egy r-permutáció, ekkor Pn. r inverziója a Cn r = C1 , C2,···, Cr vektor,
ahol
Ci E {O, 1, .... ,n-i} és

r-i

Ci = Pi - i+ Lo i, j
j=l
ahol

o = {O,hap.<p. J'
i.j 1, ha P, > Pi

Egy Pn. r -hez tartozó Cn. r előállítása a fenti képIetet követve meglehetősen egyszerű, de
kihasználhatjuk a Pn.r és Cn.r kapcsolatának egy speciális tulajdonságát. Nevezetesen, hogy ha Z;
elemeit a már l.l-ben megismert listában tároljuk, akkor c1-et úgy kapjuk, hogy megszámláljuk,
hogy ebben a listában hány elem előzi meg Pl -et, majd Pl -et töröljük a listából, c2 értékének
meghatározásához az így nyert listában meg kell számlálnunk a P2 -t megelőző elemek számát, majd
P2 -t is töröljük a listából a többi Ci -t ugyanilyen módszerrel kapjuk:

proeedure eodingi
var i,t, eount:integeri
begini
Init;
for i:=l to r do
begin
eount:=O;
t:=O;
while p[i)<>a[t) do
begin
t:=a[t);
ine(eount)
end;
eli] :=eounti
a [t) :=a [a [t) )
end;

Fig. 1.3.1.: Permutációk inverziójánakgenerálása

13
A Cn, r ~ Pn, r átalakítást végző eljárás szintén a fenti tulajdonságot használja ki:

procedure Decoding;
var i,j,t:integer;
begin
Init;
for i:=l to r
begin
t:=O;
for j :=1 to c[i] do t:=a[t];
p [i] : =a [t] ;
a [t] :=a [a [t] ];
end
end;

Fig. 1.3.2.: A C-fP átalakítást végző eljárás.

Meg kell még jegyeznünk, hogy lexikograftkusan kisebb r-permutációhoz lexikografikusan kisebb
inverzió fog tartozni, vagyis, hogy a Cn,rBPn.r megfeleltetés, ilyen értelemben rendezés tartó.
A lexikografikusan t. r-permutációt közvetlenül előállító rPermGen nevű eljárás egyegy-egy értelmű
megfeleltetés a Pen, r) és a Z =
{l,2, ...,IP(n, r)l} halmazok között. Konstruáljuk meg először
rPermGen inverzét, vagyis azt a RankrPerm nevű eljárást amely lexikografikus sorrendben
megsorszámozza Z; r-permutációit.
RankrPerm konstruálásához felhasználjuk a fent bevezetett inverziók és P(n,r) egy-egy értelmű
=
kapcsolatát. Cn, r definíciójából látható, hogy egy cp cz, ... , c -vel kezdődő Cn. r CI' Cz, ... , Ci>"" Cr
j

inverziót pontosan [Pm-i, r-i)1 olyan inverzió előz meg, amelyeknek c\ ,c Z , •.• ,c előtagjára az igaz,
I l
j

hogy clj=cj j=I,2, ..,i-Iéscl <c j ugyanis, a c +l végigfut ja a [O,l, ..,n-(i+l)] intervallum
j j

értékeit, C +Z pedig [O,1,..,n-(i+2)] intervallum on fut végig, és így tovább. Ekkor az így összeszámolt
j

esetek száma:
(n-i)*(n-(i+l))* ... *(n-(r-2))*(n-(r-l))= (n-i)! = IP(n-i,r-i)1 O
(n-r)!
Vagyis a RankrPerm eljárás a következő lesz:

Procedure RankrPerm(c:codeword, var Rank:integer);


var i:integer;
begin
Rank:=l;
for i:=l to r do Rank:=Rank+c[i]*P(n-i, r-i);
end;

Fig. 1.3.3.: A RankrPerm eljárás.

A hivatkozott P(n,k) függvény definíciója a pontosság kedvéért a következő:


nl
P(n,k) := .
(n-k)!

A RankrPerm eljárás az adott r-permutáció inverziójához rendeli a kívánt sorszámot, vagyis egy
adott r-permutáció esetén RankrPerm hívását meg kell előzze a Coding eljárás hívása.

Az rPermGen eljáráshoz a tulajdonképpen már l.2-ben is alkalmazott trial-and-error módszer


alkalmazásával jutunk. A módszert most is az inverzfüggvényre (a RankrPerm eljárás) alkalmazzuk:

14
procedure rPermGen(rank, k:integer; var c:codeword);
var i:integer;
be gin
for i:=n-k downto O do
if rank > i*p (n-k, r-k) {Trial}
then begin
c[k):=i;
if k <= r then RankrPerm(rank-i*P(n-k, r-k),k+l);
exit;
end
end;

Fig. 1.3.4.: Az rPermGen eljárás.

Azonos kiindulás után kissé eltérő gondolatmenetet találunk még [Knot1976]-ban a problémára. Az
eredeti problémához kapcsolódó feladatokat találunk még [Welll971] -ben.

Kapcsolódó versenyfeladatok:

Feladat Instrukció
KLTE91-3
KLTE92-1 Lexikografikus kombinációk felsorolása

Irodalomjegyzék az 1.3 fejezethez

[Knot197 6]: G. D. Knott (1976). A Numbering System for Permutations ofCombinations.


Communications of ACM, Vol 19, p 355.
[We1ll971]: M. B. Wells (1971). Elements of combinatarial programming. p 130.

15
1.4. Egy halmaz összes részhalmazai, particionálása

Tegyük fel, hogy az a feladatunk, hogy egy halmaz (praktikusan az {1,2, ... ,n} halmaz) összes
részhalmazait kell generálnunk lexikografikus sorrendben.
A fenti halmaz részhalmazainak reprezentációja legyen a következő:
Minden egyes részhalmazt jelöljön egy f!. = ~ ~ ...
ar számsorozat, úgy, hogy
~ < a2 < ... < ar' ís r :s;n, ahol ~ ~ ... ar az adott részhalmaz elemi. Könnyen látható, hogy ez
a jelölés egyértelmű.
Definiáljuk most, az egy halmaz részhalmazainak halmazán értelmezett a lexikografikus rendezést:
Legyen f!.= ~ ~ ... =
ap és f l1 <; ... cq két részhalmaz,
akkor
ha létezik olyan i (l :s; i :s; q) amelyre minden 1 :s; j :s; i esetén aj = cj

és vagy ai < Ci
(1 )
vagy p=i-1
akkor azt mondjuk, hogy ~ lexikografikusan megelőzi (kisebb, mint) c-t.

Mindezek alapján pl. n=4 esetén a fenti halmaz részhalmazai lexikografikusan növekvő sorrendben a
következők: 1,12,123,1234,124,13,134,14,2,23,234,24,3,34,4

A fenti halmaz részhalmazait n-jegyű bináris számokkal is reprezentálhatjuk: A '1 b2 ••• bn pontosan
akkor tartozik az A részhalmazhoz, ha bi = 1 <=> i E A (i = 1,2, .. , n)

Vegyük észre, hogya részhalmazokon értelmezett lexikografikus rendezés nem ugyanazt a sorrendet
adja, mint az őket reprezentáló bináris számokon (bit-sztringeken) értelmezett lexikografikus
rendezés.

Ha valamely feladat a részhalmazok felsorolásán kívül, nem követeli meg tőlünk a lexikografikus
rendezettséget, akkor az {1,2, ...,n} halmaz részhalmazainak felsorolása bináris
reprezentációjukban, nem más, mint az egész számok bináris alakjainak felsorolása. O-től 2n-l-ig.
Egy szám bináris alakjának keresésekor kihasználhatjuk, hogy a Pascal a Word típus esetén a
számokat éppen a nekünk megfelelő formában tárolja.
Egy kicsit bonyolultabb probléma az (l)-el defmiált rendezés szerint a részhalmazok felsorolása, ezt
valósítja meg a következő program:

Program Subset_enumeration;
Const n=13;
{ <n> elemű halmaz részhalmazait soroljuk föl lexikografikusan
A program ebben a sorrendben bármely t.-ediket képes generálni
(két részhalmaz akkor különbözik, ha van különböző elemük)
A teljesítményről: 486SX25-on n=13 esetén az összes részhalmaz
felsorolása kb 40 másodpercet vesz igenybe

var
t:longint;
i,r:integer;
b:array[l ..n] of integer; {ha az b[i]>O akkor az i-edik elem a
reszhalmazban van}
a:array[l ..n] of integer; {az elso r eleme nem mas, mint a t.
reszhalmaz }

function kettoad(x:integer) :longinti


var c:longint;i:integer;
be gin c:=l; for i:=l to x do c:=c*2; Kettoad:=c end;

16
procedure subset(t:integerivar r:integer)i
var
k:integerih:longinti
begin
for i:=l to n do b[i] :=Oi
r:=Oi
k:=li
repeat
h:=kettoad(n-k)i
if t<= h then begin b[k] :=li inc(r)i arr] :=k endi
t:=t-(l-b[k])*h-b[k]i
inc (k)
until ((k>n) or (t=O))
endi

begin
for t:=l to kettoad(n) do
begin
subset(t,r)i
writelniwrite(t,' :')ifor i:=l to r do write(a[i],' 'li
end
end.

Fig. 1.4.1.: Az {1,2, .... ,n} halmaz osszes részhalmazának felsorolása.

A fenti program az eredeti célkitűzést általánosítva alkalmas arra, hogy az {1,2, ... ,n} halmaz az (1)
szerinti rendezésben t-edik részhalmazát generálja. A program subset eljárása hívás után az a, b
globális változóban t-edik részhalmazt, az r-paraméterében pedig a t.-részhalmaz elemszámát adja
vissza.

Legyen Z; = {I, 2, .... , n}. Ekkor a Z; halmaz egy partíciója az azon halmazok
P = {7rl' 7r2, ••• , 7rm} halmaza, amelyre
7ri n 7rj = 0, ha i'1':. j
és 7r '1':.0, i=I,2, ... ,m
1

(2 )
m
és Unt
i=l
= Z;
feladatunk rögzített n esetén az összes fenti tulajdonságú halmazrendszer előállítása.

Számítsuk először ki, hányféle különböző particionálása létezik az {1,2, ... ,n} halmaznak !

Jelölje Bn a keresett partíciók számát (Bell-féle szám), ekkor n= 1 esetén nyilván B 1= 1


Tegyük fel, hogy Bl, B2, ••• , Bn_l ismert. Ekkor Hn_l-hez vegyünk egy a többitől különböző elemet,
jelöljük ezt a-val. Keressük meg H; = Hn_
{a} összes partícióit !
l U

Világos, hogy azon partíció száma, amelyekben {a} szerepel B n-l' hiszen ezeket úgy nyerhetjük,
hogy Hn_l-minden partíciójához hozzávesszük a {a} halmazt. Továbbá az {a, p}-t (p EHn_l)
tartalmazó partíciók száma, egy rögzített p -esetén Bn_2, mivel p-t összesen (n~l)-féleképpen
választhat juk ki, ezért azon partíciók száma, amelyekben ex, egy kételemű részhalmazba esik

17
( n~l) . Bn_l' és ugyanígy gondolkozva azoknak a partícióknak a száma, ahol a. egy i-elemű

részhalmazba esik (~~:). Bn_i


Vagyis H; = Hn- 1 u {a} összes partícióinak száma:

B n = ~.n
1=1
(n-l)
1-
n
1 B n-m = 1=1
(n-l) n-I
L n - 1. B n-l.= k=O
L
(n-l)
k Bk

A táblázat Bn értékeit mutatja:

12
4213597

Fig. 1.4.2.: s; értékei


A következőkben M. C. Er 1987-ben publikált [MCER1987] módszerét mutatjuk be.

Legyen a C = llC2 ••• cn kódszó a Z; egy partícióját leíró kódszava, úgy, hogy

n=4 esetén a következő táblázat mutatja a kódszavakat:

Kódszó
1111
1112
1121
1122
1123
1211
1212
1213
1221
1222
1223
1231
1232
1233
1234

Fig. 1.4.3.: Az {1,2,3,4} halmaz összes partíciói és a hozzájuk tartozó kódszavak.

A táblázatból is látható, hogy ebben a kódszó konstrukcióban 1 ~ Ci ~ i. Másszóval i E Z; nem


kerülhet 1ttbe, ha j > i. A következőkben azt vizsgáljuk, hogy a Z; halmaz összes partícióinak
kódszavai Zn_l halmaz összes partícióit leíró kódszavak sorozatából
hogyan vezethetők le a
hozzáadva cn -t a már meglévő kódszavakhoz. cn értékei az 1,2 ... , max( ll, C;... Cn-1) + 1 intervallum
értékei közül kerülnek ki.
Ezen tulajdonságok segítségével működik 4.4 algoritmusunk, amely a megfelelő kódszókat generálja.
A hivatkozott SP(m, p) eljárás definíciójában az m = max( eJ, ~ ... Cn_l) és p paraméter adja az
aktuális kódszó aktuális jegyét. Eljárásunk feltételezi a PrintPartition eljárást, amely a kódszó B
partíció konvertálást ill. az így nyert partíció megjelenítését végzi. Mindezek után eljárásunk a
következő:

18
type codeword=array[l ..max] of integeri

procedure SetPartitions(n:integer)i
var c:codewordi
procedure SP(m,p:integer)j
var i:integeri
begin
if p > n then PrintPartition(c)
else
begin
for i:=l to m do
begin
c[p] :=iiSP(m, p+1) i
endi
c[p] :=m+1i SP(m+1, p+1)
end
endi
begin
SP(O, 1)
endi

Fig. 1.4.4.: M C. Er rekurzív algoritmus az {l.2 ....•n} halmaz összes partíciójának generálásához.

A fenti Pascal kód Borland Pascal 7.0-ás verziójú fordítót használva napjaink átlagosnak mondható
teljesítményű PC-jén (486 SX 25) a következő futási időeredményeket adta:

n Futási idő
10 < 1 sec
11 < 4 sec
12 < 21 sec
13 < 130 sec

Fig. 1.4.5.: Az Er-féle rekurzív halmaz particionáló algoritmus futási ideje néhány n-re.

Mint a táblázatból is látható, a versenyfeladatok esetén akkor alkalmazható az algoritmus ha


feldatbeli n < 13.
Ha az eredeti problémát, úgy módosít juk, hogy csupán a lexikografikus sorrendben t. partíciót
keressük, akkor a fenti Er-féle algoritmus nem használható hatékonyan, hiszen ahhoz, hogy
megkapjuk a a t. partíciót le kell generáltatnunk a megelőző t-l darab partíciót is.
A lexikografikusan t. partíciót előállító algoritmust megkaphatjuk, ha megfeleltetést találunk a
természetes számok és a már ismertetett konstrukcióval előállított kódszavak között.

Az említett megfeleltetés bemutatásához vezessük be a következő jelöléseket:

Dn(r, d) :azon CIC2,,,,Cn kódszavak száma,


ahol CIC2,,,,Cr rögzített és
d = max(c ,c l 2, •. ,cr_l) (r=2, ... ,n+1; d=1, .. ,r-1)

Könnyű látni, hogy mivel minden kódszóra igaz, hogy CI = 1 ezért D; (2, 1) = En, továbbá az is igaz,
hogy Dn(n+l,d)=l (d=l, 2, ... n) ,valamint Dn(n,d)=d+l (d=l, ... ,n-l).

Határozzuk meg D; (n -1, h) -t!

19
Ekkor

Cl ,C2,··· ,cn-2 ,Cn-l ,Cn


'----v------'
max=h

(1)

vagyis cn_l helyére 1,2,,,.,h, h+ 1 kerülhet, ezek közül 1,2,,,.,h úgy, hogy maxfc, ,c2' oo,cn_l) = h
igaz marad, vagyis az ilyen kódszavak száma h* Dn(n, h),
ha cn-l = h + 1 (azaz cn_l-et is rögzítjük) , akkor az ilyen ( 1) tulajdonságú kódszavak száma
Dn (n, h + 1), vagyis összesen:

(2)

Hasonló okoskodással, kapjuk, hogy

Dn(r, d) = d * Dn(r + 1, d) + Dn(r + 1,d + 1) (r = 3,oo,n -1; d = l,oo.,r -1) (3)


Vagyis D; (r, d)értékei könnyen kiszámíthatók. Ezek alapján a sorszám ~ kódszó konverzíót végző
algoritmust könnyű elkészíteni:

procedure rank(t, n:integer; c:codeword)i


var r:integer;
begin
t:=l; d:=l;
for r:=2 to n
begin
do t:=t+([r]-1)*Dn[r+1, d];
if c[r]> d then d:=c[r]
end
end;

Az eljárás feltételezi, hogya Dn[2"n+ 1, 2"n+ 1] tömbben e D; (r, d) megfelelő értékei vannak.
Az inverz eljáráshoz, vagyis a kódszó ~ sorszám konverzióhoz, hasonlóan gondolkodva, mint az l.2
fejezetben a következő algoritmust kapjuk:

program Set_Partitionsi
const
Bell:array [0..15] of longint=
(1, 1, 2, 5, 15,
52, 203, 877, 4140, 21147,
115975, 678570, 4213597, 27644437, 190899322,
1382958545 )i
var
n:integerit:longint;r,i,j:bytei
Dn:array[1 ..18,1 ..18] of longinti
C:codewordi

procedure PreCalcD(n:integer); { A D(n) értékek kiszámítása}


var d,r:integer;
begin
Dn [2,1] :=BELL [n] ;
for d:=l to n-1 do Dn[n,d] :=d+1i
for d:=l to n do Dn[n+1,d] :=1;
for r:=n-1 downto 3 do
for d:=r-1 downto 1 do Dn[r,d]:= d*Dn[r+1,d] + Dn[r+1,d+1]i

20
endi

Procedure partition(tO:longint var d:byte)i


var r:integeri
t,m,k:longinti
Begin
t:=tO id: =1 i
for r:=2 to n do
begin
m r=O)
repeat inc(m) until t <= m * Dn[r+1,d])i
if d+1 < m then m:=d+1i
c [r] : =mr
t:=t-(m-1)*Dn[r+1,d]i
if d < m then d:=mi
endi
endi

begin
writelni write(' n:')i readln(n)i
PreCalcD(n)i c[l] :=li
for t:=l to BELL[n] do {a ciklus az összes partíciót generálja}
begin
partition(t,r)i {a t. partíció elő állítása}
for j:=l to r do
begin
write(j,'. reszhalmaz elemei:')i
for i:=l to n do if c[i]=j then write(i, " ')i
writeln
e nd r
end
end.

A programpartition(t, r) eljárása generálja a lexikografikusan t. kódszót. Az eljárás a kész kódszót a


már fent definiált codeword típusú C globális változóba teszi, míg a kódszóban leírt partíció
részhalmazainak számát az r-paraméterében adja vissza. A kódszó partícióvá alakítását a fóprogram
végzi. A fenti program egy adott n-hez tartozó {1,2, ...,n} halmaz összes partícióját előállítja úgy,
hogy végrehajtja a partition(t, r) eljárást a t= 1,2,3, .... ,Bn értékekre.
Az összes partíció generálását új algoritmusunk valamivellassabban végzi, viszont cserében a t.
partíciót közvetlenül, az ezt megelőző t-I partíció előállítása nélkül állítja elő.

A témakörhöz a következő feladat kapcsolódik:

KLTE92-7
A probléma neve: Szállítás
Mivel a probléma csupán az n<100 korlátozást tartalmazza, ezért az összes eset generálása és
ellenőrzése a fenti módszerek bármelyikévei is, nem valószínű, hogy megoldáshoz vezet akkor ha a
zsúri teszt inputadataiban a csomagok száma több, mint 13. Az előző korlátozás bevezetésévei 4.4
algoritmusunkkal a csomagok halmazának összes partícióinak előállításával és ellenőrzésévei
kiválaszthatjuk az optimálist.
Az eredeti feladat megoldásához más módszert kell keresnünk !
További kapcsolódó versenyfeladat: RUGB91-6

21
Irodalomjegyzék az 1.4 fejezethez

[MCER1987]: M.C. Er (1987) Alghorithm for generating Set Partitions. The Computer Journal
Vol. 31 No 3, pp 283

22
1.5. Gray kódok

A Gray kódok olyan k-bites bitminták sorozata, amelyek olyan tulajdonságúak, hogy az egymást
követőek egymástól egyetlen bitben különböznek. Például a következő 3-bites Gray kódok
alkalmasak arra, hogy a O-tói 7-ig a számokat kódolják:

Gray kódok Sorszám Decimális


érték
000 O O
100 1 4
101 2 5
001 3 1
011 4 3
010 5 2
110 6 6
111 7 7

Fig. 1.5.1.: Gray kódok

A Gray kódok között speciális tulajdonságúak a Ciklikus Gray kódok, amelyekre a fentieken kívül az
is igaz, hogy az utolsó és az első is egyetlen bitben különbözik egymástól. A fentiek nem Ciklikus
Gray kódok. A továbbiakban csak Ciklikus Gray kódokkal foglalkozunk, ezért a rövidség miatt csak
Gray kódokként hivatkozunk rájuk.

Gray kódok Sorszám Decimális


érték
000 O O
001 1 1
011 2 3
010 3 2
110 4 6
111 5 7
101 6 5
100 7 4

Fig. 1.5.2.: Ciklikus Gray kódok

Itt megjegyezzük, hogy a Gray kódok O-val (minden bit O) kezdődnek és a következő sza.bállyal
generálhatóak: Minden egyes lépésben az adott Gray kódból egyetlen bit negálásával apjuk a
következő Gray kódot. Meg kell határoznunk ennek a bitnek a pozícióját. Erre a pozícióra pedig az
igaz, hogy pontosan fele annyiszor kel1 változtatni, mint a tőle közvetlenül jobbra ál1ót. Ez a módszer
viszonylag könnyen programozható, de megvan az a hátránya, hogyan-edik Gray kódot csak a
megelőző n-l kód legyártása után adja. Ismét két problémát fogalmazhatunk meg.:

(a) Soroljuk fel az összes k-bites Gray kódot


(b) Írjuk fel ak-bites Gray kódok közül az n. et.

Természetesen, a (b) probléma az általánosabb. De néha, ha csupán az (a) -problémát kell


megoldanunk akkor ha az (a)-t megoldó algoritmusunk egyszerűbb és gyorsabb, mint az
általánosabb (b)-t megoldó algoritmusunk, akkor érdemesebb azt használni (lásd például permutáció
generálás esetét).
Keressünk a fent már leírt módszemél egyszerűbb et az (a) problémához, valamint minél egyszerűbb
megoldást a (b)-problémához!
Jelöljük G(k) = (go. gp ...• g2k_) -val a k bites Gray kódokat.

23
Ekkor G-t a következő rekurzióval
defmiálhatjuk:
G(1) = (0,1)
{ G(n + 1) = (Ogo,Ogpo (1)
.. ,Og2n_l' Ig2n_, , ... , Igo)

Vagyis ezzel egyben módszert adtunk az (a) probléma megoldásához. Az (1) képletből könnyen
megkap hatjuk az m-edik Gray kód n. bitjét:

g(m, n) = (mmOd2"
2n- <1
)
( 2)
'
Vagyis a (b) problémát akár egy, a (2) formulát használó algoritmussal is megoldhat juk,

Legyen
D(n) = (ct.,~,... ,d2n), úgy, hogy di gi hányadik biten tér el gi-l -től.

akkor

D(1) =1
{ D(n+ 1) = (D(n),n+ (3)
1,D,ev(n)), ahol D,ev(n):= D(n) jordítottja

Ha

és
n
g; = (bn,bn_ p ••• ,'1), hogy i = 'Llj2j (4)
j=O
akkor

b.J =/.J xor l,J- I j = 1,2, .... ,n

Ez utóbbi formula teremt kapcsolatot egy szám bináris alakja és a hozzá tartozó Gray kód között.Az
ezen a formulán alapuló algoritmusokat megvalósító program oknak megfelelő típusválasztás esetén
(Pascal esetén a Word típus ilyen) nem kell tartalmazniuk bináris számmá alakító eljárást, hiszen azt
a számítógép változó-értékadáskor elvégzi. Sőt ha észreveszzük, hogya bj-t előállító sor egy bináris
l-bittel jobbratolást fed, akkor a programunk a szám bináris alakjából egyetlen utasítással
előállíthatja a megfelelő Gray kódot bitmintáját. Mivel a feladatok között találtam olyat, amely
megoldásához az (a) ill. (b) problémát is meg kell oldani, ezért a Gray kód generáló algoritmusunkat
ebbe ágyazva közöljük:

USEC92-1
A probléma neve Bit Twiddler:
Származása: 1992 ACM East Central Regional Programming Contest

A probléma lényege k-biten (k<=15 ) generálni a Gray kódokat az n.-től az m.-ig, n, m, k a program
inputjai. A program outputja a megfelelő Gray kódok decimális alakja:A problémát két
részproblémára lehet bontani:

(1) k-biten az n-edik Gray kód generálása


(2) valamely k-bites Gray kódból kiindulva a következő m darab k-bites Gray kód generálása

Mivel a feladat k-ra vonatkozó korlátja (k<=15) elegendően kicsi, ezért használhat juk a már fent
emIített pascalbeli Word típu st, valamint a memóriában elfér az összes l5-bites Gray-kód, amely

24
tartalmazza (l)-miatt az összes 14, 13, 12, ..,2, l-bites Gray kódot. Az init eljárás generálja a 15-
bites Gray kódokat, ahogy ígértük egyetlen értékadással. A program többi eljárása a
követelményeknek megfelelő outputot (az adott Gray kód decimális alakját) állítja elő.

program Twiddler;
uses ert;
type gray = array[O ..O] of word; {Csak a cím miatt}
var g: Agray;
b,j,t,i: word;

proeedure init;
{ A gray kódok előállítása}
var i:word;
begin
for i:=O to maxint do gA[i] := (i xor (i shr 1));
end;

proeedure put(tol,ig,biten:word);
var i:word;
begin
for i:=tol to ig do writeln(gA[i]);
end;

be gin
elrseri
getmem(g,65535);
init;
repeat
write('Mettől? ');readln(t);
write('Meddig? ');readln(i);
write('Hány biten? ')ireadln(b);
if b=O then halt(O);
put(t,i,b-1)
until false
end.

Fig. 1.5.3.: Twiddler.pas

25
2. Geometriai algoritmusok

Bevezetés

A számítógépeket egyre többen és egyre gyakrabban használják olyan alapvetően geometriai eredetű,
nagy mennyiségű adat feldolgozásával kapcsolatos problémák megoldására, mint az alakfelismerés, a
térinformatikai, térképészeti vagy háromdimenziós szimulációs problémák. A geometriai
algoritmusok szintén nagyon fontosak az olyan komplex fizikai rendszerek tervezésében és a
elemzésében, mint például az épületek, autók, gépek és integráltáramkörök. Az ilyen
programrendszerekben a tervezők a fizikai objektumoknak megfeleitetett gépi objektumokkal
dolgoznak. Ezen gépi objektumok megfelelő szintű számítógépes kezelése, megjelenítése igazán
komoly feladat.
Az ilyen alkalmazások olyan alapvető objektumai, mint a pontok, szakaszok vagy poligonok és a
hozzájuk kapcsolódó alapvető eljárások adják az általában a nehezebbek közé sorolható geometriai
versenyfeladatok megoldásának alapjait.
A geometriai problémákat könnyen vizualizálhatók, de ez néha nem könnyíti meg a megoldás
keresését, inkább csak a probléma megértésében segítenek. Nagyon sok probléma megoldása, amely
"szabadkézzel" pillanatok alatt megoldható egy darab papír és ceruza segítségével (pl. eldönteni,
hogy egy pont egy poligon belsejében van -e vagy sem) követel egyáltalán nem triviális számítógépes
programot.
Néhány geometriai versenyfeladat megoldásához elegendő a középiskolai koordinátageometriából
tanult alapvető függvények, eljárások (pl. pontok távolsága a síkon, egyenes és pont távolsága,
háromszög területe) pontos (le)programozása. Ezek megoldása inkább a szimulációs problémák
megoldásához hasonlít.
További "geometriai" problémák megoldását tisztán vagy nagyrészt kombinatorikai algoritmusok
adják, ezért az ilyen problémák elemzése előtt érdemes a "Kombinatorikai algoritmusok" című
fejezetet (még egyszer) áttanulmányozni.
A geometriai tartalmú versenyfeladatok harmadik csoportja olyan problémákból áll, amelyek
megoldásához az első csoportbeli alapvető geometriai függvények pontos megvalósítása, valamint
kombinatorikai alapismeretek szükségesek.
A legtöbb algoritmus, amit tanulmányozni fogunk a legegyszerűbb geometriai objektumokkal fog
dolgozni a két dimenziós véges, de megfelelően kiterjedt síkon. A legalapvetőbb geometriai
objektumot a pontot egy számpárral fogjuk jellemezni (a pont 'koordinátái' a derékszögú koordináta
rendszerben). A szakasz reprezentációja egy pontpár, amelyeket az adott szakasz összeköt. A poligon
esetünkben pontok listája, és feltételezzük, hogy az egymásután következő pontok szakaszokkal
vannak összekötve, valamint, hogy az utolsó pontot az elsővel szintén egy szakasz köti össze, így
alkotva egy zárt alakzatot.
Az egységesség és az egyszerűség kedvéért rögzítsük le most, hogy hogyan fogjuk ezeket az
objektumokat a programjainkban reprezentálni.
A poligonok reprezentációja egy tömb. Használható lenne még láncolt lista is, de a listák alapvető
műveleteinek programozása a pascalban egy kicsit sok adminisztrációt követel meg a programtói,
ezért a tömbök használata a programokat egyszerűbbé teszi. Ha valamely probléma pontoknak egy
halmazát érinti, akkor a reprezentációban szintén az array[O ..max] of pont definíciót fogjuk
alkalmazni, ahol max valamilyen elegendően nagy szám.

Tehát programjaink a következő reprezentációkat fogják használni:

type pont = record


x :integeri
y: integer
endi

type szakasz = record


pl:ponti
p2:pont

26
endi

var poligon: array{O ..max] of ponti

Fig. 2. O.J.: Geometriai objektumok reprezentáció ja.

Furcsának tűnhet, hogy a pontok a koordinátarendszer rácspontjaira korlátozódnak. A valós


reprezentáció ugyanígy használható lenne, de az egész értékeket használata sokkal átláthatóbb és
hatékonyabb (az egész számok műveleteit a számítógép sokkal gyorsabban végzi, mint a
lebegőpontosakat) programot eredményez, nem beszélve arról, hogy a versenyfeladatok általában
megelégszenek az egész értékű geometriai programozással is.

27
2.1. Szakaszok metszete

Az első probléma melyet tárgyalni fogunk az egyik legalapvetőbb probléma ezért számos más
algoritmus is hivatkozni fog rá, ezért nagyon fontos a precíz kidolgozása .. A probléma a következő:
Adott két szakasz, amelyek ponttá is fajulhatnak (kezdő és végpontjuk egybeesik) eldöntendő, hogy
metszik-e egymást vagy sem. A következő ábra néhány lehetséges előfordulást mutat:


Fig. 2.1.1.: Szakaszok a síkon.

A kézenfekvő algoritmus esetünkben az, hogy számítsuk ki annak a két egyenesnek a metszéspontját,
amelyek tartalmazzák a kérdéses szakaszokat, majd vizsgáljuk meg, hogy a szakaszaink
tartalmazzák-e ezt a metszéspontot. Amennyiben a kérdéses egyenesek párhuzamosak, akkor azt kell
vizsgálnunk, hogy valamely szakasz végpontja a másik szakaszra esik-e. Az egyenesek
metszéspont jának kiszámítása visszavezethető egy kétismeretlenes egyenletrendszer megoldására,
amely útmutatást pl. [BELT1989]-ben találhatunk.

function metszet (pO,pl,p2,p3: pont) :booleanj


var
nev,a,b,c,d,x,y:reali
flagl,flag2,flag3,flag4:booleanj
begin
a:=pl.y-pO.Yi b:=pO.x-pl.x;
c:=p3.y-p2.Yi d:=p2.x-p3.Xi

nev:=a*d-b*ci {az egyenletrendszer matrixanak determinansa}

if (abs(a)+abs(b»O) and (abs(c)+abs(d»O)


{ha egyik szakasz sem pont}
then
if nev<>O {nem parhuzamosak}
then begin
{ (x,y) a tartalmazo egyenesek metszespontja }
y:=(a*(c*p2.x+d*p2.y)-c*(a*pO.x+b*pO.y))/nevi
x:=(d*(a*pO.x+b*pO.y)-b*(c*p2.x+d*p2.y))/nevi

flagl:=((pO.x<=x) and (x<=pl.x)) or


((pl.x<=x) and (x<=pO.x));
flag2:=((p2.x<=x) and (x<=p3.x)) or
((p3.x<=x) and (x<=p2.x))j
flag3:=((pO.y<=y) and (y<=pl.y)) or
((pl.y<=y) and (y<=pO.Y))j
flag4:=((p2.y<=y) and (y<=p3.y)) or
((p3.y<=y) and (y<=p2.Y))j
metszet:=flagl and flag2 and flag3 and flag4

end
else {a szakaszok parhuzamosak}

28
if a*p2.x+b*p2.y=a*pO.x+b*pO.y
then begin
flagl:=((( (pO.x<=p2.x) and (p2.x<=pl.x) ) or
( (pl.x<=p2.x) and (p2.x<=pO.x) ) ));

flag2:=((( (pO.x<=p3.x) and (p3.x<=pl.x) ) or


( (pl.x<=p3.x) and (p3.x<=pO.x) ) ));

flag3:=((( (p2.x<=pO.x) and (pO.x<=p3.x) ) or


( (p3.x<=pO.x) and (pO.x<=p2.x) ) ));

flag4:=((( (p2.x<=pl.x) and (pl.x<=p3.x) ) or


( (p3.x<=pl.x) and (pl.x<=p3.x) ) ));

metszet:= flagl or flag2 or flag3 or flag4;


end
else
metszet:=false
else {valamelyik szakasz pont l}
if ((abs(a)+abs(b))>O) and (abs(c)+abs(d)=O)
{a masodik szakasz pont}
then
if a*p2.x+b*p2.y=a*pO.x+b*pO.y
then
metszet:=((pO.x<=p2.x) and (p2.x<=pl.x)) or
((pl.x<=p2.x) and (p2.x<=pO.x))
else
metszet:=false
else
if (abs(a)+abs(b)=O) and (abs(c)+abs(d»O)
{az elso szakasz pont}
then
if c*pl.x+d*pl.y=c*p2.x+d*p2.y
then metszet:=((p2.x<=pl.x) and (pl.x<=p3.x)) or
((p3.x<=pl.x) and (pl.x<=p2.x))
else metszet:=false
else {mindketto pont}
metszet:=(p2.x=p3.x) and (pO.y=p2.y)
end;

Fig. 2.1.2.,' Szakaszok metszetén ek vizsgálata.

Sajnos a túl sok eset vizsgálata és kezelése eléggé bonyolult pascal kódot eredményez. A
versenyfeladatok megoldásához nem mindig szükséges a fentihez hasonló, általános algoritmus (pl.
ha a szakaszok nem fajulnak pontokká, akkor az algoritmus és vele együtt a kód is lényegesen
egyszerűbb). A fuggvény alkalmazhatóságát megnehezíti, hogy a kód nem eléggé átlátható és ezzel
együtt nehezen debug-olható,
Az algoritmust megvalósító fuggvényt könnyedén át lehet alakítani úgy, hogy amennyiben van
metszéspont annak koordinátáit adja is vissza, hiszen pl. nem elfajuló esetben a fuggvény x,y
változójában a metszéspont koordinátái előállnak.
A fentinél talán egyszerűbb és szintén általános algoritmust mutat be R. Sedgewick [SEDG1988]
művében. A közölt algoritmus nem számítja ki explicit módon a szakaszokat tartalmazó egyenesek
metszéspontját, hanem a szakaszvégpontok elhelyezkedése alapján dönti el, hogy van-e metszéspont.
Sedgewick közli az algoritmus pascal kódját is, de az sajnos nem működik. Viszont az algoritmusnak
megvan az az előnye a fentivel szemben, hogy a (helyes) pascal kódja talán kevesebb sorból állna.

29
Kapcsolódó problémák:

P2.2.1. Adott n szakasz, eldöntendö, hogy zárt poligont alkotnak-e.


P2.2.2. Adott n szakasz, eldöntendö, hogy páronként metszik-e egymást.
P2.2.3. Hány metszéspont ja van egy adott n csúcsú konvex poligon átlóinak.

Irodalomjegyzék a 2.1.1. fejezethez.

[SEDG 1988]: Robert Sedgewick: Algorithms. Second Edition. 1988. p. 349.


[BELTI989]: Bélteky Károly: Analitikus Geometria és Lineáris Algebra. 1989.

30
2.2. Poligon és pont

A versenyeken gyakran tűnnek fel olyan feladatok, melyek arra az alapproblémára vezethetők vissza,
amelyben az algoritmusnak el kell döntenie, hogy egy adott pont egy adott (konvex vagy konkáv)
poligon belsejében van-e. A kérdést 'emberi' intelligenciával, szabadkézzel meglehetősen egyszerű
eldönteni, viszont a gépi megoldás már nem triviális.
Az egyik legegyszerűbb algoritmus a következő:

l. Ellenőrizzük, hogy a vizsgálandó pont nem esik-e a poligon valamely csúcsára vagy
oldalára. Ha igen akkor a pont az adott poligon belső pontja.

2. Keressünk egy olyan pontot a síkon, amely biztosan az adott poligonon kívül van. Mivel a
poligont véges sok pont feszíti ki, ezért valamely irányban egy elegendően távoli pont
biztosan a poligonon kívülre esik. Legyen ez a pont Q

3. A vizsgálandó pontból (P) húzzunk egy egyenest Q-ba.

4. Vizsgáljuk meg, hogy a PQ egyenesnek van-e közös pontja a poligon csúcsaival, ha igen
keressünk egy a mostani Q-tól különböző új külső pontot-o 2. pont

5. Számláljuk meg a PQ egyenes és a poligon oldalainak metszéspontjainak számát. Ha ez


páros akkor Papoligonon kívül volt, páratlan esetben P a poligon belső pontja.

A 4.pontbeli feltétel az ábrán is látható kivételek miatt kell ellenőriznünk. A programunkban egy
adott P-hez a megfelelő Q-t a következő módszerrel keressük meg:

4.1. Megkeressük azt a poligon[i] csúcsot, amely a poligon legjobboldalibb csúcsa

4.2.q.x:= poligon[i] .x+1, q.y:=poligon[i].y

4.3. Ellenőrizzük, hogy Q megfelel-e a fentieknek, ha nem q. y: =q. y+ 1, majd .....-;3.3.pont.

Mivel a poligon véges sok csúcsból áll, ezért a 4.3 ciklus véges sokszor (legfeljebb n-szer, ha n a
csúcsok száma) fog végrehajtódni, véges sok lépésben megtaláljuk a megfelelő Q pontot.

Q
p
------..---,"\

Fig. 2.2. J.: Pont és Poligon elhelyezkedései a síkon

A fenti algoritmus egy lehetséges megvalósítását mutatja a következő program:

31
program insidei
uses crti
const max=20i

type pont=record x,y:integer endi

var poligon: array[O ..max] of ponti


p,q:ponti
count,i,n:integeri
ctrl, ctr12:booleani

procedure InputPoligoni
var i:integeri
begin
clrscri
write('n :')ireadln(n)i
writeln('-------------------------------------------')i
for i:=l to n do
begin
writeln('Az " i , '-edik csucs koordinatai')i
write('x: ')ireadln(poligon[i] .X)i
write('y: ')ireadln(poligon[i] .y)i
endi
poligon[O] :=poligon[n]i
endi

procedure InputPonti
begin
writeln('A pont koordinatai')i
write('x: ')ireadln(p.x)i write('y: ')ireadln(p.y)i
endi

begin
InputPoligoni
InputPonti

ctr12:=falsei i:=Oi
repeat
ctr12:=ctr12 or metszet2(p,p,poligon[i],poligon[i+l])i
.i nc t í.j r
until (ctr12) or (i=n-l)i
if ctr12 then writeln('*8enne')
else be gin
q.x:=-maxinti
for i:=l to n do
begin
if poligon[i] .x > q.x
then
begin q.x:=poligon[i] .x+li q.y:=poligon[i].y endi
endi
repeat
q.y:=q.y+li
ctrl:=falsei
for i:=l to n do ctrl:=ctrl or
metszet(poligon[i],poligon[i],p,q)i
until not ctrli

32
if (p.x = q.x) and (p.y q.y) then writeln('*Kivul')
else begin
count:=O;
for i:=O to n-l do
if metszet(poligon[i], poligon[i+l], p,q) then inc(count);
if odd(count) then writeln('*Benne ') else writeln('*Kivul ');
end
end;
end.

Fig. 2.2.2.,' A fenti program eldönti, hogy egy adott pont egy adott poligon belsejében van e.

Az algoritmus egyetlen feltételezést támaszt az input adatokkal szemben, feltételezi, hogy azok a
megadott sorrendben egy zárt, önmagát nem metsző alakzat valamilyen rögzített körbejárás szerinti
csúcsai. Az alábbi poligonokat algoritmusunk inputjaként meg lehet úgy adni, hogy kielégítsék e
feltételt, ezért ezek az esetek is kezelhetők:

Sedgewick az előző problémánál hivatkozott könyvében erre a problémára is ad megoldást.


Sedgewick algoritmusa csakúgy, mint a fenti, egy félegyenest húz a vizsgálandó pontból egy fiktív, a
poligonon garantáltan kívülre eső ponton át, ám bármilyen legyen is ez (mindegy, hogy a poligon
csúcsain megy át vagy a poligon valamely oldalát tartalmazza ), ennek a félegyenesnek és a
poligonnak számolja össze a metszéspontjait, úgy, hogy közben figyeli az előforduló speciális
eseteket, de sajnos a fenti ábrán láthatókhoz hasonló esetekkel nem tud mit kezdeni.

Kapcsolódó problémák:

P2.2.1. Írjunk hatékony algoritmust, amely eldönti, hogy egy pont egy konvex poligon belsejében
van-el
P2.2.2. Írjunk olyan pascal függvényt, amely eldönti, hogy két háromszögnek van-e metszéspont ja.

Kapcsolódó versenyfeladatok

Feladat Instrukció
RUGB92-3 Itt csak azt kell vizsgálni, hogy a sík egy adott pontja egy adott háromszög
belsejébe esik-e, ezért a feladat jóval egyszerűbb módszerrel is megoldható
IOAG91-2

33
2.3. Ponthalmaz konvex burka

Ebben a fejezetben egy olyan algoritmust kell készítenünk, amely meghatározza egy adott
ponthalmaz konvex burkát. A konvex burok nem más, mint egy konvex poligon, melynek csúcsai az
adott ponthalmaz pontjai közül valók és a többi pont a poligon oldalaira vagy belsejébe esik.

Fig. 2.3.1.: Ponthalmazok konvex hurka.

A pontosság kedvéért egyértelművé kell még tennünk azt az esetek, amikor a ponthalmaz 3 vagy több
pontja egy egyenesbe esik a ponthalmaz határán. Ilyenkor algoritmusunk outputját csak a poligon
csúcsaira eső pontok 'alkotják. Azaz a 2.3.1 b) ábrán látható ponthalmaz konvex burkát az
ABCDEFGH-val megjelölt pontokkal azonosítjuk.
A konvex burok egyik tulajdonsága, hogy bármely a poligonon kivüli egyenest a poligon felé
mozgatva az a poligont egy csúcsában érinti. Ezt a tulajdonságot alkalmazva a koordináta
tengelyekkel párhuzamos egyenesekre kapjuk, hogy a pontok közül azok, amelyek minimális ill.
maximális x illetve y koordinátákkal rendelkeznek biztosan a burokhoz fognak tartozni. Ezt a tényt
használjuk fel a soron következő algoritmusunk kiindulásaként.
Algoritmusunk bemenete pontok egy halmaza, amelyet egy array[J..max] alpont fog reprezentálni.
A kimenete pedig egy poligon. Minthogy a poligon típus is egy előbbihez hasonló tömb típus, ezért
az algoritmus a bemenetként kapott tömb elemeit egyszeruen átrendezi, úgy, hogy az első M
tömbelem fogja a ponthalmaz konvex burkát reprezentálni.
Látnunk kell azt, hogy azzal, hogy megtaláltuk és valamilyen módon megjelöltük a ponthalmaz
konvex burkát alkotó pontokat, még nem oldottuk meg teljesen a problémát. Az így megjelölt
pontokat ugyanis úgy kell sorrendbe rendeznünk, hogy azok valóban poligont alkossanak. Azaz a
2.3.1 b) ábrán látható ponthalmazt inputként megadva a GBCEDFAH output nem elfogadható.
Tehát a csúcspontként megjelölt pontokat, még rendeznünk kell. Ha ezen pontok (x, y) derékszögű
koordinátáit (r, d) polárkoordinátákká alakítjuk (ahol d az Origótól mért távolság, r pedig a pont
helyvektorának valamely rögzített egyenessei vett szöge), majd a pontokat a hozzájuk tartozó r érték
alapján rendezzük akkor a kívánt sorrendet kapjuk. Megfontolandó az, hogy az egész probléma nem
vezethető-e vissza a ponthalmaz pontjainak (r, d) szerinti lexikografikus rendezésére!
Algoritmusunk azonban explicit módon semmilyen rendezést nem fog tartalmazni, lesz azonban egy
kódrésze, amely a fent leírtak szerinti legkisebb r értékü pontot választja ki, anélkül, hogy
trigonometrikus fuggvényeket használna. A trigonometrikus fuggvények kiküszöbölése az
algoritmusból a megvalósított programot gyorsabbá, hatékonyabbá teszi. Az algoritmus:

1 Válasszuk ki a minimális y koordinátájú pontok közül azt amelynek a legkisebb x


koordinátája van.. A fentiek alapján ez a pont biztosan a konvex burok csúcspontja lesz.
Legyen ez a burok első pontja.

2 A burok második pontját úgy kaphat juk, hogy a burok első pontján át húzunk egy x-
tengely jel párhuzamos egyenest (az előző pont garantálja, hogy ezen egyenes alatt, már
nincsenek pontok), majd ezt az egyenest forgassuk az előző pont körül az óramutató

34
járásával ellentétes irányban addig, amíg valamely pontba ütközünk. Ha egyszerre több
pontba ütköztünk akkor válasszuk ki a távolabbi pontot, és ez lesz a burok következő pontja.
3. A burok következő pontját úgy kapjuk, hogy egyenesünket az utoljára burokpontként
megjelölt pont körül forgatjuk az eddigiekkel megegyező irányban addig amíg valamely
pontba nem ütközünk. Ha egyszerre több pontot is elért az egyenesünk, akkor mindig a
távolabbi pontot választ juk a burok következő pontjaként.

4. Ismételjük a 3.-beli eljárást addig míg a kiindulási pontunkat el nem értük.

Fig. 2.3.2.: Ponthalmaz konvex burkát előállító algoritmus.

Az algoritmusbeli feltételek garantálják, hogy a burokbeli pontokat a helyes sorrendben állítjuk elő.
Az algoritmust megvalósító pascal program technikai megoldása az, hogy az így megjelölt pontokat
az input tömb elejére cseréli és a már beválasztott pontokat nem vizsgálja újra. A következő ábra az
algoritmus működését szemlélteti:

1 1

3 3

1 1

4 4

5
5 3 3

1 1

Fig. 2.3.3.: A "csomagoló" eljárás működése.

Visszatérve a konvex burok értelmezésére, megadására, az algoritmust és így a programot is


egyszeruen át lehet alakítani, úgy, hogy az a burok csúcsoktói különböző pontjait is előállítsa

35
outputként. Egyszerűen akkor, amikor egyenesünk több ponttal ütközik egyszerre, akkor az érintett
pontok közül a legközelebbit kell a burok következő csúcspontjaként megjelölnünk.
Mindezek után az algoritmust megvalósító pascal program:

program becsomagoli
const
max=100i
type
pont=record
x:integeri
y:integer
erid r
var
inp,out:texti
ok,s:stringi
n,i,j,k:integeri
poligon = array[O ..max] of ponti

procedure str_to_pont(s:stringivar q:pont)i


var v,j,xl,x2:integeri
sl:stringi
begin
v:=pos(',',s)i sl:=copy(s,l,v-l)i
delete(s,l,v)i val(sl,xl,j)i
val(s,x2,j)j
q.x:=xli q.y:=x2i
e nd r

function theta(pl,p2:pont) :reali


var
dx,dy,ax,ay:integeri
t:reali
be gin
dx:=p2.x-pl.xiax:=abs(dx)i
dy:=p2.y-pl·Yiay:=abs(dY)i
if (dx=O) and (dy=O) then t:=-l else t:=dy/(ax+aY)i
if dx<O then t:=2-t else if dy<O then t:=4+t;
theta:=t*90.00
endi

function d(pl,p2:pont) :reali


var
dx,dy:reali
begin
dx:=p2.x-pl.Xi
dy:=p2.y-pl·Yi
d:=sqrt(dx*dx+dy*dy)
endi

function csomag (c:integer) :integeri


var
i,min,m:integeri
minszog,v,mintav,th:reali
t:ponti
begin
min:=li

36
for i:=2 to n do
if poligon[i] .y<poligon[min].y then min:=i
else
if poligon[i] .y=poligon [min] .y
then
if poligon[i] .x<poligon[min].x then min:=i;
m:=O;
poligon[n+l] :=poligon[min];
minszog:=-l;
repeat
inc (m) ;
t:=poligon[m];poligon[m] :=poligon[min];poligon[min] :=t;
min:=n+l;
v:=minszog;
minszog:=360.00imintav:=O;
for i:=m+l to n+l do
begin
th:=theta(poligon[m],poligon[i])i
if th >= v then
if th < minszog then
begin
min:=ii
minszog:=th;mintav:=d(poligon[m],poligon[min])
end
else
if th minszog
then
if c*d(poligon[m],poligon[i]) > c*mintav
then
begin
min:=i; minszog:=thi
mintav:=d(poligon[m),poligon[min))
end
end
until min=n+l;
csomag:=m
end;
begin
assign(inp, 'pontok.inp');
assign(out, 'burok.out');
reset(inp); rewrite(out);
repeat
readln(inp,s);
n:=O;
while s<>'*' do
begin
inc (n);
str_to_pont(s,poligon[n))i
readln(inp,s)
end;
for i:=l to csomag(-l) do
writeln(out,poligon[i) .x,',' ,poligon[i) .y) i
writeln (out, '*')
until eof(inp)i
close(inp);close(out);
end.

37
Fig. 2.3.4.: A Konvex Burok algoritmus.

A program a 'pontok imp' nevű imput állományból olvassa be a ponthalmazokat, és a 'burok.out'


nevű output állományba írja a megfelelő konvex burok csúcspontjait. Az állományok szerkezete a
következő:

Az input állomány blokkokból áll, egy blokk egy ponthalmaz pontjainak megadását tartalmazza,
úgy, hogy egy sorban pontosan egy pont kordinátái találhatók vesszővel elválasztva. A blokk végét '*'
jelzi.
Az output állomány az inputként megadott ponthalmazok konvex burkát tartalmazza . Egy sorban
pontosan egy pont koordinátái vesszővel elválasztva. A burok végét egy új sorban egy '*' jelzi.

A program csomag(c:integer) eljárása végzi a fent jellemzett eljárást. A c:integer paraméter


értékétől függ, hogy az output állományba, melyik megadás szerint kerüljenek a poligon pontjai. c >
O esetén, csak a poligon csúcspontjai, c < O esetén azon pontok is, amelyek a poligon oldalaira
esnek

A probléma általánosításának egyik lehetséges módja a több dimenziós térre történő kiterjesztése.
Könnyű belátni, hogy a fenti algoritmus több dimenziós térben is helyesen működik, ha elkészítjük a
fenti pascal program több dimenziós, hipersíkokat is kezelő változatát.

Kapcsolódó Problémák:

P2.3.l. Írjunk olyan algoritmust, amely online módon adja meg az inputként megadott ponthalmaz
konvex burkát. Az input pontokat egymás után egyesével adjuk meg az eljárásunknak és az eddig
megadott pontok konvex burkát adja meg lépésenként, módosítva azt minden újabb pont után ha
szükséges. lásd [SHAM1977]

Kapcsolódó versenyfeladatok:

Feladat Instrukció
IOAG91-2 A feladat megoldása mindkét eddig ismertetett algoritmus alkalmazását
megköveteli
ACMF92-4 A konvex burok algoritmus explicit alkalmazása.
KLTE93-2

Irodalomjegyzék a 2.3 fejezethez

[SHAM1977]: Shamos, M. 1. 1977, Computational geometry


[GRAHI972]: Graham, R. L. An efficent algorithm for determining the convex hull ofa fmite
planar set. Inform. Processing Letters 1 1972. P 132-133
[PREP 1977]: Prepatra, F. P., Hong S. J.: Convex hulls of fmite sets in two and three dimensions.
Communications of ACM, Vol 20. Num 2., p 87-93

38
3. Gráfalgoritmusok

Bevezetés

A programozói versenyek "nehezebb" feladatainak legnagyobb hányadát a gráfelméleti feladatok


teszik ki. Ezek a feladatok lehetnek expliciten gráf elméleti fogalmakkal megfogalmazottak
(olyanokkal, mint feszítőfa vagy legrövidebb út), vagy valamilyen a mindennapi életből vett köntösbe
bújtatottak.
A gráf, mint matematikai objektum nem más, mint csúcsok és élek véges halmaza. A csúcsok a
legkülönfélébb más objektumok lehetnek, egyetlen kikötésünk, hogy valamilyen megkülönböztetésük
létezzen: legyen nevük vagy más azonosítójuk. A gráf egy éle összeköttetést, kapcsolatot reprezentál
a gráf pontosan két csúcsa között.

A fenti ábrán látható ABCDF, G, EHI csúcspontokkal jellemzett rajzok alkothatnak egy kettő vagy
három gráfot. Tekinthetjük például ABCDFG-t egy gráfnak. Ezt a gráfot definiálhat juk úgy, hogy
felsoroljuk a csúcsait: A, B, C, D, F, G majd az éleit AF, AD, BC, BD, Bf, CD.
Egy X csúcspontból pontosan akkor vezet út egy Y csúcsba egy gráfban, ha létezik a csúcsoknak egy
olyan listája, amelyben az egymás után következő csúcsok a gráfban éllel vannak összekötve. A gráf
összefüggő minden csúcsából létezik út minden más csúcsába. Pl a fenti ABCDF gráf összefüggő,
míg az ABCDFEHI gráf nem összefüggő. A gráf egy egyszerű útja azon út amelyhez tartozó
listában nincs ismétlődő csúcspont. A gráf egy kör-e azon egyszerű út, amelyben a kezdő és a
végpont megegyezik (vagyis a listában egyetlen ismétlődés van). Azt a gráfot, amelyben egyetlen kör
sincs és összefüggő fá-nak nevezzük (a nem összefüggő, körmentes gráf ot erdő-nek nevezzük). A
gráf feszítőfá-ja a gráf azon részgráfja, amely a gráf összes csúcsát tartalmazza, és pontosan annyi
élt a gráf élei közül, hogy az így nyert részgráf összefüggő legyen. Könnyen látható, hogy n csúcsú
gráf feszítőfájának pontosan n-l éle van. A feszítőfa másik ismert tulajdonsága, hogy bármely új élt
hozzáadva már kört kapunk. Azt a gráf ot, amely rendelkezik az összes lehetséges éllel teljes gráf-
nak, amelyik viszonylag kevés éllel rendelkezik ritka gráf-nak, amelyik elég sok éllel rendelkezik
sűrű gráf-nak nevezzük.
A gráf ok gépi reprezentációiról nagyon hasznos dolgokat tudhatunk meg [SEDGI988]-ban valamint
[NIE 11977] -ben.
A gráf algoritmusok bonyolultsága (itt most bonyolultságon az adott körülmények közötti legrövidebb
idejű megvalósíthatóságot kell érteni, ennek egyik leglényegesebb komponense a kód rövidsége és
egyszerűsége) nagyban függ attól, hogy a gráfok milyen reprezentációját választottuk. Általában a
legegyszerűbb kódot azon algoritmusok eredményezik, amelyekben a gráf reprezentációjaként
valamilyen mátrixos (szomszédsági vagy összefüggőségi) megoldást választottunk. Persze vannak
problémák, amelyeknél a listás reprezentáció elkerülése sokkal "költségesebb" lenne, mint annak
megvalósítása.

Irodalomjegyzék a 3. fejezethez

[SEDGI988]: Robert Sedgewick: Algorithms pp418 - 421


[NIEI1977]: J. Nievergelt, J. C. Farrar, E. M. Reingold: Matematikai Problémák Megoldásainak
Számítógépes Módszerei. 72-73 oldal

39
3.1. Mélységi keresés

Az egyik legklasszikusabb gráf elméleti algoritmus a keresés. Ebben a problémában olyan kérdésekre
kell az algoritmusnak válaszolnia, mint van-e az adott gráfban kör, vagy melyek a gráf összefüggő
komponensei.
Fogalmazzuk meg először, mit is kell most keresésen értenünk! Legyen adott a gráfnak két csúcsa,
nevezetesen START és GOAL, a feladat megkeresni a STARTból a GOALba vezető utat, vagyis azt
a listát amelynek első elem START utolsó eleme pedig GOAL és az egymás után következő
listaelemeket a gráfban él köti össze.
l. Meg kell vizsgálnunk, hogya START csúcs megegyezik-e a GOAL-al, ha igen, akkor
kereső eljárásunk már véget is ért hiszen a keresett listának egyetlen elemből áll: a ST ART
csúcsból.
2. Ha nem vagyunk ilyen "szerencsések", akkor keressük meg a START csúcs összes
szomszédját, ezt a folyamatot kiterjesztésnek nevezzük. Az így nyert csúcsokat a START
csúcs "gyermekeinek", "utódjainak" vagy "rákövetkezőinek" nevezzük. Ennek a lépésnek az
eredménye egy lista.
3. Eztán a fenti két lépést alkalmazzuk az így nyert új csúcsokra, úgy, hogya 2. lépés után az
újabb listát az előző listához fűzzük.

p.z S1 csúcs kiterjesztése

Fig. 3.1.1.: Altalános kereső eljárás működése

A módszerek különbözőségének okát abban kell keresnünk, hogy a 2. lépés után kapott csúcsokat
milyen sorrendben terjesztjük ki. A két legismertebb kereső stratégia a szélességi és a mélységi
keresés. A mélységi keresés alkalmával mindig olyan "messze" haladunk a gráfban a START
csúcstól, amilyen messze csak lehet, vagyis a fenti ábrán mélységi stratégia szerint az S II csúcs
következne kiterjesztésre, szélességi stratégia szerint pedig az S2. De mindennél többet mond talán az
algoritmus formális leírása.

INPUT: A gráf két csúcsa START és GOAL


FELADAT: Meghatározni, hogy létezik-e egyszerű út START és GOAL között.
OUTPUT: Igen vagy Nem
1. Legyen NYILTAK egy lista, első eleme legyen START
Legyen ZÁRT szintén egy üres lista
2. Ha NYILTAK üres, akkor algoritmus vége és a válasz Nem
3. Vedd az első csúcsot a NYILTAK-ból legyen ez A. Szúrd A-t a ZÁRT lista elejére.
a) Ha A = GOAL akkor az algoritmus vége és a válasz Igen.
b) Hajtsd végre a kiterjesztést A-ra, ennek eredménye legyen az UTÓDOK listája.
b1. Vedd ki az UTÓDOK listájából azon csúcsokat, melyek szerepelnek a
ZÁRT listában
b2. Fűzd az UTÓDOK listáját a NYILTAK listája elé.
b3 Menj 2. -re

Fig. 3.1. 2.: A mélységi keresés algoritmusa.

40
A fenti algoritmus, nem használja ki az élek reflexivitását, vagyis irányított gráf okra is tökéletesen
működik. A mélységi keresési stratégiát természetesen nem csak arra használhatjuk, hogy
megkeressük két csúcs között egy gráfbeli utat. Használhatjuk pl. arra is, hogy megtudjuk, hogy egy
adott gráf tartalmaz-e kört. Ugyanis ha a 3bl-ben ténylegesen ki kell vennünk valamely csúcsot a
ZÁRT listából, akkor ez azt jelenti, hogy ehhez a csúcshoz egy újabb útvonalon eljutottunk, vagyis,
hogy a gráf kört tartalmaz. Azt is könnyen beláthatjuk, hogy a stratégia segítségével leválogathatjuk
egy gráf összefiiggő komponenseit: Meg kell jelölnünk a kiterjesztett csúcsokat és ha a NYILTAK
listája már üres és még van a gráfban meg nem jelölt csúcs, akkor ez azt jelenti, hogy ez a meg nem
jelölt csúcs a gráf eddigitől különböző komponensében van.
A témával kapcsolatban nincs már más hátra, mint a fenti ellenőrzéseket elvégző pascal program:

program deptfirsti
{
input formatum (a graf megadasa)
1. sor csucsok szama (v)
2. sor elek szama (e)
2+1. sor elso ,1: a ket csucs sorszama amelyeket osszekot
[space]-szel elvalasztva.
2+2. sor masodik,l

2+e sor e-edik ,1

const maxV=200;

type link=Anode;
node=record
v :integer;
next :link
end;

var inp,out:text;
id,k,l,v,e,last:integer;

components:integer; {ennyi osszefuggo komponens}

graph: array[l ..MaxV] of link;


order: array[l ..MaxV] of integer;
cycle:boolean {=true ha van benne kor };

procedure Str2Vertex(s:string;var k,j:integer);


var v,h:integer;
xl,x2:integer;
sl:string;
begin
v:=pos(' ',s); sl:=copy(s,l,v-l);
delete(s,l,v); val(sl,k,h); val(s,j,h)
end;

procedure ReadInput;
var
j,i,x,y:integer;
s:string; t:link;
begin
assign(inp, 'deptlst.inp'); reset(inp); readln(inp,v);

41
readln(inp,e); for i:=l to v do graph[i] :=NIL;
for j:=l to e do
begin
readln(inp,s);Str2Vertex(s,x,y);
new(t);tA.v:=x; tA.next:=graph[y];graph[y] :=t;
new(t);tA.v:=y; tA.next:=graph[x];graph[x] :=t;
end;
end;

Procedure visit(k:integer);
var t:link;
begin
inc(id);order[k] :=id; t:=graph[k];
while t<>NIL do
begin
if order[tA.v]=O then visit(tA.v) else cycle:=true;
t:=tA.next
end
end;

Procedure Conclusion;
begin
writeln(out, 'Osszefuggo komponensek: ',components); {/ A /}
if cycle then writeln('kor :van ')
else if components=l then writeln('fa') else writeln('erdo');
writeln(out)
end;

begin
assign(out, 'deptlst.out'); rewrite(out);
ReadInput;
id:=O; last:=O; components:=O;
for k:=l to v do order[k] :=0;
for k:=l to v do
begin last:=idi
if order[k]=O
then begin
visit(k); inc(components);
writeln(components, osszefuggo reszgraf:');
for 1:=1 to v do
if (order[l]<=id) and (order[l]>last) then write(l, I ')i
writeln;
end
end;
Conclusion;
close(out)
end.

Fig. 3.1.3.: A mélységi keresés.

A program feltételezi, hogy az input fileban megadott csúcsok és élek egyetlen gráfhoz tartoznak. A
program az előzőek szerinti stratégiát használva alkalmas:

-a gráf bejárására (minden csúcsot pontosan egyszer meglátogat)


- a gráf összefüggő komponenseinek leválogatására

42
- eldönti egy gráfról, hogy van-e benne kör; (nem sorolja fel a köröket)
- ezek alapján eldönti, hogy a gráf fa ill erdő-e.

A gráf reprezentációja most egy tömb. A tömb elemei listák, minden csúcshoz pontosan egy. a lista
elemei az adott csúcs szomszédjai. Vagyis a fenti gráfot programunkban a következő tömb
reprezentálja:

graph[1]= 6 -> 4
graph[2]= 3 -> 4 -> 6
graph[3]= 2 -> 4
graph[4]= 2 -> 3
graph[5]= 8 -> 9
graph[6]= 1 -> 2
graph[7]=
graph[8]= 5 -> 9
graph[9]= 5 -> 8

Könnyű látni, hogy ez a reprezentáció alkalmas irányított gráf ok gépi reprezentálására is. Irányított
gráfok esetén egy adott élt, csak egyszer kell szerepeltetni a struktúrában.
Az order[l..MaxVJ tömb tartalmazza a gráf bejárási sorrendjét, kezdetben minden eleme O. A gráf
azon összefuggő komponensének mélységi bejárását, amely a paraméterként megadott csúcsot
tartalmazza a rekurzívan működő visít eljárás végzi. A visít eljárást (a kiterjesztést) a l-es csúcsra
végrehajtva az eljárás megkeresi az l-es csúcs szomszédjai közül, azt amely még nem volt megjelölve
az order tömb segítségével. Ha talál, ilyet akkor erre végrehajtja a visít eljárást, ha nem talál ilyet
akkor ez azt jelenti, hogy, az adott csúcs minden szomszédját bejártuk, vagyis vissza kell lépnünk egy
szinttel "feljebb" (backtrack) ....
Egy gráf összefüggő komponenseinek leválogatására alkalmas Warshall algoritmusa is [NIE21977]

Kapcsolódó versenyfeladatok

Feladat Instrukció
KLTE91-5 Megoldható más, nem gráf elméleti módszerrel is. A gráf os módszer megvalósítása
hosszabb és bonyolultabb módszert követel.
IOAG91-4 A feladatban egy gráf legtöbb csúcsot tartalmazó összefuggő komponensét kell
megkeresnünk, ez a fenti program segítségével lehetséges. Mivel a feladatban a
gráf a szomszédsági mátrixával adott, ezért Warshall algoritmusa is nagyon jól
alkalmazható.
ACMF91-1 Útkeresés.
KLTE92-3 Körkeresés
KLTE92-5 Útkeresés.
USEC92-3 Útkeresés.
TUBP92-5 Összefuggő komponensek szétválasztása.
ACMF92-5 Vegyünk sorra minden élt a feladat irányított gráfjában. Majd az adott élt hagyjuk
el az eredeti gráfból . Ha ebben a gráfban létezik út az adott él végpontjai között
akkor az adott él által reprezentált függőség redundáns.

Irodalomjegyzék a 3.1 fejezethez

[NIE21977]: J. Nievergelt, J. C. Farrar, E. M. Reingold: Matematikai Problémák Megoldásainak


Számítógépes Módszerei. 77 - 78 oldal.

43
3.2. Optimális keresés

Ebben a problémakörben a gráf két csúcsa közötti viszonyt már nem csak az él léte vagy nemléte
jellemzi, hanem az esetleges él költsége is. Az előző fejezetbeli algoritmussal szembeni kérdéseink
pedig úgy módosulhatnak, hogy:

- Mennyi két megadott csúcspont közötti minimális út költsége?


- Mennyi egy adott csúcsot (csúcsokat) tartalmazó kör minimális költsége?

Algoritmusunk az előző fejezetbelihez a struktúrájában hasonlít, viszont az élek költségeinek kezelése


és költségoptimalizálás bonyolultabb adatszerkezeteket eredményez:

INPUT: Két gráfbeli csúcspont: START és GOAL


FELADAT: Minimális költségű út keresése START és GOAL között
OUTPUT: Egy lista, amely a minimális költségű utat tartalmazza START-ból GOAL-ba,
amennyiben létezik út.
Típus: LlSTAELEM=(csúcs_neve, éLazonosító, mutató (a csúcs őse), összköltség)
1. Legyen NYILTAK egy lista LISTAELEM típusú tagokból. Legyen ennek első eleme
(START, NIL, NIL, O). Legyen a ZÁRTAK listája hasonló szerkezetű üres lista.
2. Ha a NYILTAK listája üres, akkor algoritmus vége és a válasz: Nincs útvonal!
3. Vedd a NYILTAK első elemét, legyen ez X. Szúrd X-et a ZÁRTAK elejére
a) Ha X.csúcs_neve megegyezik GOAL, akkor algoritmus vége és a keresett lista a
ZÁRTAK listája alapján alőállítható
b) Hajtsd végre a kiterjesztést X-re, ennek eredménye legyen az UTÓDOK listája. Az
UTÓDOK listájának minden elemére készíts egy LISTAELEM elemet, amelyeben:
(
csúcs_neve := az adott csúcs neve
, éLazonosító:= a felhasznált él azonosítója
, mutató := X.csúcs_neve.
, költség := X.összköltség + a felhasznált él költsége
)
Az így nyert elemeket szúrd a NYILTAK listájába, úgy, hogya lista az elemek összköltség
mezője szerint rendezett maradjon (növekvő sorrendben).
Folytasd a 2. lépéstől.

Fig. 3.2.1.: Az optimális keresés algoritmusa

Az ezt megvalósító program:

!$A+,B-,D+,E+,t-,G-,I+,L+,N+,O-,R-,S+,V+,X-}
{$M 16384,O,655360}
PROGRAM optimal;
US ES ert;

input: a programban Inputtile nevu txt file amely a terkepre vonatkozo adatokat
tartalmazza
minden varoshoz sorok tartoznak ,melyek a kovetezoket tartalmazzak:
nev
<szomszed varos neve>
<ut hossza>
end

CONST
Inputtile = 'terkep.dat';
Outputtile = 'result.txt';
Vegtelen = Maxint;
TYPE
Szam INTEGER;
Szam2 REAL;

44
VarosNev string[80];
VarosMut AVarosListaElem;
VarosListaElem = RECORD
nev VarosNev;
ut Szam2;
kov VarosMut
END;
Mutato ATag;
Tag RECORD
nev VarosNev;
szomszedok VarosMut;
szulo Nev;
koltseg Szam2;
kov Mutato;
END;
VAR
eredmuta,atm,
varosok,nyiltak,zartak Mutato;
honnan, hova Tag;
megegyszer,Debug BOOLEAN;
Valasz,Nyom CHAR;
Kit INTEGER;
out text;

FVNCTION VtKoltseg (a,b Tag) :Szam2; {utkoltseg a varos es b varos kozott)


VAR
mut :Mutato;
sz :VarosMut;
tavolsag: Szam2;
i:integer;
BEGIN
i:=-2; mut:=Varosok;
WHILE (mutA.nev <> a.nev) AND (mut<>NIL) DO mut .- mutA.kov;
IF mut <> NIL THEN
BEGIN
sz:=mutA.szomszedok;
WHILE (szA.nev <> b.nev) AND ( sz <> NIL) DO sz:=szA.kov;
IF sz <> NIL THEN tavolsag := SZA.ut
ELSE BEGIN writeln(out, 'tavolsag-----> error'); tavolsag .- Vegtelen; END
END
ELSE BEGIN writeln(hiba); exit end;
UtKoltseg:=tavolsag;
END;

FUNCTION MutVaros (varos VarosNev) Mutato;


VAR
atm atag Mutato;
BEGIN
atm:=Varosok;
WHILE (atmA.nev <> varos) and (atmA.kov <> NIL) DO
atm := atmA.kov;
NEW(atag);
atagA := atmA; atagA.kov NIL; MutVaros := atag
END;

PROCEDVRE IllesztVaros( n :Varosnev; os: Tag; VAR NyiltAktElem :Mutato);


VAR
atm:Tag;
mut:Mutato;

45
BEGIN
mut := MutVaros(n); atm := mutA;
IF NyiltAktElem = NIL THEN
BEGIN
NEW( mut );mutA := atm; mutA.koltseg :=UtKoltseg(os, atm) + os.koltseg;
mutA.kov .- NyiltAktElem;{=nil}; NyiltAktElem := mut;NyiltAktElemA.szulo .- os.nev;
END
ELSE
BEGIN
IF os.koltseg + UtKoltseg( atm, os) > NyiltAktElemA.koltseg
THEN Illesztvaros(n, os, NyiltAktElemA.kov)
ELSE
BEGIN
NEW ( mut ); mutA := atm; mutA.kov .- NyiltAktElem;
mutA.szulo := os.nev; mutA.koltseg .- oS.koltseg+UtKoltseg(atm, os);
NyiltAktElem := mut;
END
END
END;

FUNCTION Zartban_Van(s:Varosnev):boolean;
var atm:mutato;
BEGIN
atm:=Zartak;
WHILE (atmA.nev<>s) and (atmA.kov<>NIL) DO atm:=atmA.kov;
IF atmA.nev=s THEN Zartban Van:=TRUE ELSE Zartban_Van:=FALSE;
END;

procedure KiirLista(atm:Mutato; s:string);


begin
writeln(out,s,' Lista a ',kit, '. kiterjesztes utan');
WHILE atm <> Nil DO
BEGIN
WRITELN(out, 'Csucs.nev: ' atmA.nev,', koltseg: atmA.koltseg:5:0,
'; ose:',atmA.szulo);
atm := atmA.kov
END;
writeln(out,' ');
end;

PROCEDURE Kiterjeszt;
VAR
AktSzomszed VarosMut;
atm Mutato;
ose Tag;
BEGIN
AktSzomszed:=NyiltakA.szomszedok;
atm := MutVaros( NyiltakA.nev); ose:=atmA;
ose.koltseg:=nyiltakA.koltseg; atm:=Nyiltak;
Nyiltak := NyiltakA.kov;
atmA.kov := Zartak; Zartak .- atm;
WHILE AktSzomszed <> nil DO
BEGIN
IF not Zartban_Van(AktSzomszedA.nev) THEN IllesztVaros (AktSzomszedA.nev, ose,
Nyiltak) ;
AktSzomszed .- AktSzomszedA.kov
END
END;

46
PROCEDURE Engine;
Var
atm Mutato;
BEGIN
IF Debug THEN READLN; writeln(out,' ');
KiirLista (Nyiltak, ,A Nyilt Lista'); KiirLista (Zartak, 'A Zart Lista');
IF (nyiltak~.nev <> hova.nev) AND (nyiltak<>NIL)
THEN BEGIN
Kiterjeszt; inc(kit);
KiirLista(Nyiltak, 'A Nyilt Lista');KiirLista(Zartak, 'A Zart Lista');
Engine;
END;
END;

PROCEDURE Adatbe;
VAR
mut:Mutato;
sor:Nev;
vmutato:VarosMut;
Inp:text;
Utpuffer: Szam2;
BEGIN
Varosok := NIL;
ASSIGN(inp,InputFile); RESET(inp);
WHILE NOT EOF(inp) DO
BEGIN
NEW(mut); READLN( inp, mut~.nev);
mut~.koltseg := O; mut~.szulo:='KACOR'; mut~.szomszedok := NIL;
READLN( inp, sor);
WHILE sor<>'end' DO
BEGIN
NEW(vmutato); vmutato~.nev := sor;
READLN( inp, vmutato~.ut); vmutato~.kov := mut~.szomszedok;
mut~.szomszedok := vmutato;
READLN( inp, sor)
END;
mut~.kov := Varosok; Varosok .- mut
END;
CLOSE( inp ); Varosok .- mut
END;

PROCEDURE NyiltZartInit;
VAR
mut Mutato;
BEGIN
Nyiltak := MutVaros( honnan.nev );
Nyiltak~.szulo:='START-CSUCS';
Zartak := NIL; mut := MutVaros ( hova.nev ); Hova := mut~;
mut := MutVaros (honnan.nev); honnan := mut~
END;

Function Eredmeny:mutato;
VAR
result:Mutato;
min:szam2;
ok, mut,ez,minmut,temp :Mutato;
os :VarosNev;
BEGIN

47
new(result) ;
result~:=nyiltak~; result~.kov:=NIL;
min:=maxint; minmut:=NIL; os:=result~.szulo;
REPEAT
ez:=zartak;
WHILE (ez<>NIL) DO
BEGIN
IF (ez~.nev=os) AND (ez~.koltseg < min)
THEN BEGIN min:=ez~.koltseg; minmut:=ez END;
ez:=ez~.kov
END;
IF minmut<>NIL THEN
BEGIN
NEW(temp) ;
temp~:=minmut~; ok:=result;
result:=temp; temp~.kov:=ok;
os:=resultA.szulo
END;
UNTIL ( (minmut r , nev=honnan. nev) OR (minmut=NIL) );
eredmeny:=result
END;

BEGIN (main)
Adatbe;
megegyszer:=TRUE;
WHILE meg egyszer DO
BEGIN
ClrScr;
kit:=O;
WRITE ('Nyomkovetes (i/n) ,);
READLN ( Nyom );
IF UpCase(nyom)='I' THEN begin Debug:=TRUE; assign(out, "); end
ELSE begin Debug:=False; assign(out,OutputFile) end;
append(out);
WRITE ('start: '); READLN (honnan. nev) ;
WRITE ('cel: '1; READLN ( hova. nev); WRITELN;
NyiltZartInit;

Engine;

IF Nyiltak<>NIL
THEN BEGIN
eredmuta:=Eredmeny;
writeln('KESZEN VAGYUNK');
writeln(out, 'A KITERJESZTESEK SZAMA ',kit) ;
atm := eredmuta;
WHILE atm <> Nil DO
BEGIN writeln(out,atmA.nev,', atm~.koltseg:5:2); atm .- atmA.kov END;
END
ELSE writeln(out, 'Nincs ut');

WRITE('Megegyszer? ');
READLN(valasz);
IF UpCase(valasz)='I' THEN megegyszer:=TRUE ELSE megegyszer:=FALSE;
END;
writeln(out, '----'); close(out);
END.

Fig. 3.2.2.: Az optimális keresést megvalósító pascal program

48
A programnak inputként a következő gráf ot adtam meg:

Csucs.nev: e, koltseg: 16; ose:b


A program a következő outputot generálta: Csucs.nev: c, koltseg: 18; ose:e

Nyomkovetes (i/n): n A Zart Lista Lista a 3. kiterjesztes utan


start: a Csucs.nev: e, koltseg: 9; ose:a
cel: i Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START-
OUTPUT CSUCS

A Nyilt Lista Lista a O. kiterjesztes utan


Csucs.nev: a, koltseg: O; ose:START- A Nyilt Lista Lista a 3. kiterjesztes utan
CSUCS Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: d, koltseg: 16; ose:e
A Zart Lista Lista a O. kiterjesztes utan Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: e, koltseg: 16; ose:b
A Nyilt Lista Lista a 1. kiterjesztes utan Csucs.nev: c, koltseg: 18; ose:e
Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: e, koltseg: 9; ose:a A Zart Lista Lista a 3. kiterjesztes utan
Csucs.nev: e, koltseg: 9; ase:a
A Zart Lista Lista a 1. kiterjesztes utan Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: a, koltseg: O; ose:START-
CSUCS CSUCS

A Nyilt Lista Lista a 4. kiterjesztes utan


A Nyilt Lista Lista a 1. kiterjesztes utan Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: b, koltseg: 8; ose:a Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: e, koltseg: 9; ose:a Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: c, koltseg: 18; ose:e
A Zart Lista Lista a 1. kiterjesztes utan Csucs.nev: h, koltseg: 19; ose:c
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: f, koltseg: 20; ose:c
CSUCS Csucs.nev: i, koltseg: 21; ose:c

A Nyilt Lista Lista a 2. kiterjesztes utan A Zart Lista Lista a 4. kiterjesztes utan
Csucs.nev: e, koltseg: 9; ose:a Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: c, koltseg: 14; ose:b Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: e, koltseg: 16; ose:b Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START-
A Zart Lista Lista a 2. kiterjesztes utan CSUCS
Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START-
CSUCS A Nyilt Lista Lista a 4. kiterjesztes utan
Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: f, koltseg: 16; ose:e
A Nyilt Lista Lista a 2. kiterjesztes utan Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: e, koltseg: 9; ose:a Csucs.nev: c, koltseg: 18; ose:e
Csucs.nev: c, koltseg: 14; ose:b Csucs.nev: h, koltseg: 19; ose:c
Csucs.nev: e, koltseg: 16; ose:b Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: i, koltseg: 21; ose:c
A Zart Lista Lista a 2. kiterjesztes utan
Csucs.nev: b, koltseg: 8; ose:a A Zart Lista Lista a 4. kiterjesztes utan
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: c, koltseg: 14; ose:b
CSUCS Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a
A Nyilt Lista Lista a 3. kiterjesztes utan Csucs.nev: a, koltseg: O; ose:START-
Csucs.nev: c, koltseg: 14; ose:b CSUCS
Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: f, koltseg: 16; ose:e A Nyilt Lista Lista a 5. kiterjesztes utan

49
Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: e, koltseg: 16; ose:b A Zart Lista Lista a 7. kiterjesztes utan
Csucs.nev: c, koltseg: 18; ose:e Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: h, koltseg: 19; ose:c Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: f, koltseg: 20; ose:c Csucs.nev: d, koltseg: 16; ose:e
Csucs. nev: i, koltseg: 21; ose:c Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: f, koltseg: 22; ose:d Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a
A Zart Lista Lista a 5. kiterjesztes utan Csucs.nev: a, koltseg: O; ose:START-
Csucs.nev: d, koltseg: 16; ose:e CSUCS
Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a A Nyilt Lista Lista a 7. kiterjesztes utan
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: c, koltseg: 18; ose:e
CSUCS Csucs.nev: h, koltseg: 19; ose:c
Csucs. nev: f, koltseg: 20; ose:c
Csucs.nev: g, koltseg: 21; ose:f
A Nyilt Lista Lista a 5. kiterjesztes utan Csucs. nev: i, koltseg: 21; ose:c
Csucs.nev: f, koltseg: 16; ose:e Csucs.nev: f, koltseg: 22; ose:d
Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: c, koltseg: 18; ose:e A Zart Lista Lista a 7. kiterjesztes utan
Csucs.nev: h, koltseg: 19; ose:c Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: f, koltseg: 20; ose:c Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: i, koltseg: 21; ose:c Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: f, koltseg: 22; ose:d Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: e, koltseg: 9; ose:a
A Zart Lista Lista a 5. kiterjesztes utan Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: d, koltseg: 16; ose:e Csucs.nev: a, koltseg: O; ose:START-
Csucs.nev: cf koltseg: 14; ose:b CSUCS
Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a A Nyilt Lista Lista a 8. kiterjesztes utan
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: h, koltseg: 19; ose:c
CSUCS Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: g, koltseg: 21; ose:f
A Nyilt Lista Lista a 6. kiterjesztes utan Csucs.nev: if koltseg: 21; ose:c
Csucs.nev: e, koltseg: 16; ose:b Csucs.nev: f, koltseg: 22; ose:d
Csucs.nev: ef koltseg: 18; ose:e Csucs. nev: h, koltseg: 23; ose:c
Csucs.nev: h, koltseg: 19; ose:c Csucs. nev: i, koltseg: 25; ose:c
Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: g, koltseg: 21; ose:f A Zart Lista Lista a 8. kiterjesztes utan
Csucs. nev: i, koltseg: 21; ose:c Csucs.nev: c, koltseg: 18; ose:e
Csucs.nev: f, koltseg: 22; ose:d Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: f, koltseg: 16; ose:e
A Zart Lista Lista a 6. kiterjesztes utan Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: f, koltseg: 16; ose:e Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: d, koltseg: 16; ose:e Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: c, koltseg: 14; ose:b Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: e, koltseg: 9; ose:a Csucs.nev: a, koltseg: O; ose:START-
Csucs.nev: b, koltseg: 8; ose:a CSUCS
Csucs.nev: a, koltseg: O; ose:START-
CSUCS
A Nyilt Lista Lista a 8. kiterjesztes utan
Csucs.nev: h, koltseg: 19; ose:c
A Nyilt Lista Lista a 6. kiterjesztes utan Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: e, koltseg: 16; ose:b Csucs.nev: g, koltseg: 21; ose:f
Csucs.nev: c, koltseg: 18; ose:e Csucs.nev: i, koltseg: 21; ose:c
Csucs.nev: h, koltseg: 19; ose:c Csucs.nev: f, koltseg: 22; ose:d
Csucs.nev: f, koltseg: 20; ose:c Csucs.nev: h, koltseg: 23; ose:c
Csucs.nev: g, koltseg: 21; ose:f Csucs.nev: i, koltseg: 25; ose:c
Csucs.nev: i, koltseg: 21; ose:c
Csucs.nev: f, koltseg: 22; ose:d A Zart Lista Lista a 8. kiterjesztes utan
Csucs.nev: c, koltseg: 18; ose:e
A Zart Lista Lista a 6. kiterjesztes utan Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: f, koltseg: 16; ose:e Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: d, koltseg: 16; ose:e Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: c, koltseg: 14; ose:b Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: e, koltseg: 9; ose:a Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START- Csucs.nev: a, koltseg: O; ose:START-
CSUCS CSUCS

A Nyilt Lista Lista a 7. kiterjesztes utan A Nyilt Lista Lista a 9. kiterjesztes utan
Csucs.nev: c, koltseg: 18; ose:e Csucs.nev: i, koltseg: 20; ose:h
Csucs.nev: h, koltseg: 19; ose:c Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: f, ko1tseg: 20; ose:c Csucs.nev: g, koltseg: 21; ose:f
Csucs.nev: g, koltseg: 21; ose:f Csucs.nev: i, koltseg: 21; ose:c
Csucs.nev: i, koltseg: 21; ose:c Csucs.nev: f, koltseg: 22; ose:d
Csucs.nev: f, koltseg: 22; ose:d Csucs.nev: h, koltseg: 23; ose:c

50
Csucs.nev: g, koltseg: 24; ose:h
Csucs.nev: i, koltseg: 25; ose:c

A Zart Lista Lista a 9. kiterjesztes utan


Csucs.nev: h, koltseg: 19; ose:c
Csucs.nev: c, ko1tseg: 18; ose:e
Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: c, koltseg: 14; ose:b
Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START-
CSUCS

A Nyilt Lista Lista a 9. kiterjesztes utan


Csucs.nev: i, koltseg: 20; ose:h
Csucs.nev: f, koltseg: 20; ose:c
Csucs.nev: g, koltseg: 21; ose:f
Csucs.nev: i, koltseg: 21; ose:c
Csucs.nev: f, koltseg: 22; ose:d
Csucs.nev: h, koltseg: 23; ose:c
Csucs.nev: g, ko1tseg: 24; ose:h
Csucs.nev: i, koltseg: 25; ose:c

A Zart Lista Lista a 9. kiterjesztes utan


Csucs.nev: h, koltseg: 19; ose:c
Csucs.nev: c, koltseg: 18; ose:e
Csucs.nev: e, koltseg: 16; ose:b
Csucs.nev: f, koltseg: 16; ose:e
Csucs.nev: d, koltseg: 16; ose:e
Csucs.nev: c, ko1tseg: 14; ose:b
Csucs.nev: e, koltseg: 9; ose:a
Csucs.nev: b, koltseg: 8; ose:a
Csucs.nev: a, koltseg: O; ose:START-
CSUCS

A KITERJESZTESEK SZAMA 9
a, 0.00
b, 8.00
c, 14.00
h, 19.00
i, 20.00

51
Függelék

Ábrák, programok listája

Fig. 1.1.1.: Fike algoritmusa Rohl módosításaival 7


Fig. 1.1.2.: A lexikografikus felsorolás négy lépése 7
Fig. 1.1.3.: Permutációk lexikografikusan 8
Fig. 1.2.1.: Rohl algoritmusa (1978) 10
Fig. 1.2.2.: Wells féle IPERM2NUM függvény (1971) II
Fig. 1.3.1.: Permutációk inverziójának generálása 13
Fig, 1.3.2.: A C~P átalakítást végző eljárás 14
Fig. 1.3.3.: A RankrPerm eljárás 14
Fig. 1.3.4.: Az rPermGen eljárás 15
Fig. 1.4.1.: Az {1,2, ,n} halmaz összes részhalmazánakfelsorolása 17
Fig. 1.4.2.: Bn értékei 18
Fig. 1.4.3.: Az {l,2,3,4} halmaz összes partíciói és a hozzájuk tartozó kódszavak 18
Fig. 1.4.4.: M. C. Er rekurzív algoritmus az {1,2, ,n} halmaz összes partíciójának generálásához 19
Fig. 1.4.5.: Az Er-féle rekurzív halmaz particionáló algoritmus futási ideje néhány n-re 19
Fig. 1.5.1.: Gray kódok 23
Fig. 1.5.2.: Ciklikus Gray kódok 23
Fig. 1.5.3.: Twiddler.pas 25
Fig. 2.0.1.: Geometriai objektumok reprezentációja 27
Fig. 2.1.1.: Szakaszok a sikon 28
Fig. 2.1.2.: Szakaszok metszetének vizsgálata 29
Fig. 2.2.1.: Pont és Poligon elhelyezkedései a sikon 31
Fig. 2.2.2.: A fenti program eldönti, hogy egy adott pont egy adott poligon belsejében van e 33
Fig. 2.3.1.: Ponthalmazok konvex burka 34
Fig. 2.3.2.: Ponthalmaz konvex burkát előállító algoritmus 35
Fig. 2.3.3.: A "csomagoló" eljárás működése 35
Fig. 2.3.4.: A Konvex Burok algoritmus 38
Fig. 3.1.1.: Általános kereső eljárás müködése 40
Fig. 3.1. 2.: A mélységi keresés algoritmusa 40
Fig. 3.1.3.: A mélységi keresés 42
Fig. 3.2.1.: Az optimális keresés algoritmusa 44
Fig. 3.2.2.: Az optimális keresést megvalósító pascal program 48

Problémák listája

P 1.1.1. Írjunk olyan pascal programot, amely az 1.1.2 ábra alapján lexikografikus sorrendben generálja egy
halmaz partícióit 7
P 1.2.1. Írjunk olyan pascal függvényt, amely az elözöek alapján generálja aK. sorszámhoz tartozó
lexikografikus permutációját valamely M halmaznak ! 12
P2.2.1. Adott n szakasz, eldöntendö, hogy zárt poligont alkotnak-e 30
P2.2.2. Adott n szakasz, eldöntendö, hogy páronként metszík-e egymást... 30
P2.2.3. Hány metszéspont ja van egy adott n csúcsú konvex poligon átlóinak 30
P2.2.!. Írjunk hatékony algoritmust, amely eldönti, hogy egy pont egy konvex poligon belsejében van-e! 33
P2.2.2. Írjunk olyan pascal függvényt, amely eldönti, hogy két háromszögnek van-e metszéspont ja 33
P2.3.1. Írjunk olyan algoritmust, amely online módon adja meg az inputként megadott ponthalmaz konvex
burkát. Az input pontokat egymás után egyesével adjuk meg az eljárásunknak és az eddig megadott
pontok konvex burkát adja meg lépésenként, módosítva azt 38

52
Name: Public key USSC85 - 1
decryption

Files:
program key.pas
input key. in
output key. aut

Task:

Some important messages have be en encoded using a public key encryption algorithm.
Your job is to decode them. Messages are composed of blocks of plain text. Each block is
transformed into an integer C. There is also an integer secret key, S, and a publicly known
integer modulus, M. To decode a block C, calculate the integer P using the formula

P=CS (mod M)

Each plaintext integer P is converted into letters and punctuation by considering it


as a number in radix 100. The radix 100 digits have character correspondences as follows:
01"" (period), 02="," (camma), 03=" II (space), 04="A", 05="8", ... ,29="Z"

The first character in a block is the least significant digit. For example the
p1aintext integer 40506 translates to "CBA".
Input will consist of one or more messages. Each message is represented by severa1
integers. The order of these integers is as fo11ows:

Integer 1 : Modulus M as described above (or -1 if there are no more


messages) .
M < sqrt(maximum positive integer)
Integer 2 Secret key S as described above. O<S<M
Integers 3 to n Encoded blocks, C, as described above. O < C < maximum positive
integer
Integer n+1 -1

The integers for each message are in free format, separated by spaces. Each line of
input ends with a slash ( "/" ). There are between 1 and 30 integers on each line.
For each message, there should be a message separator indicating the message number.
Each message is to be divided into words and output on lines of 78 characters. Words in the
input are sequences of non-space characters delimited by spaces. Words in the output are to
be separated by single spaces or new lines. Words must be packed as densely as possible on a
line without splitting. Right justification is not required. Hint: No multiple preci sion or
80ating point arithmetic is required for this problem.

Samples:

INPUT

77 13 52 39 5 31 31 12 22 31 31 23 II 57 31 23 12 58 57 31 37 39 21 31 31 31 /
60 71 71 31 10 39 39 28 31 31 31 58 57 52 31 23 39 31 41 39 58 57 31 31 23 39 /
31 23 II 57 31 60 12 28 31 39 37 31 23 II 57 12 21 31 68 60 21 23 63 51 31 23 /
II 57 31 48 73 12 41 42 31 47 21 39 5 52 31 37 39 69 31 62 73 58 68 22 31 39 /
53 57 21 31 23 II 57 31 71 60 50 63 31 28 39 10 1 31 -1/
-1 I
OUTPUT

MESSAGE NUMBER 1
NOW IS THE TIME FOR ALL GOOD MEN TO COME TO THE AID OF THEIR PARTY. THE QUICK BROWN
FOX JUMPS OVER THE LAZY DOG.

Name: Krypto Player USSC85 - 2

Files:
program krypto.pas
input krypto.in
output krypto.out

Task:

Krypto is a Parker Brothers card game played wi th a deck containing the positi ve
integers from l to 25 (some more than once). The object of the game is to combine the five
cards in your hand by addition, subtraction, mul tiplication, and division to obtain a
specific number.
Play proceeds as follows. One player is designated as the dealer. The dealer gives
every player in the game five cards fa ce down. After alI players have received their hands,
the dealer turns the next card in the deck fa ce up so alI the players can see it. Everyone
then tries to combine their five cards in order to obtain the number on the face-up card.
The first player to find a solution speaks up and announces it, showing the hand as (s)he
goes. If the solution checks out, that player wins the hand, and the deal is passed to the
left.
For example, assume you were dealt 15, 9, 4, 3, and ll. The fa ce up card is a 5. One
solution might be 15 + II - 9 + 3 = 4 (15 plus II is 26, minus 9 is 17, plus 3 is 20,
divided by 4 is 5). Note that expressions are read from left to right without precedence or
grouping of any kind, and alI intermediate results must be integers.
)
Your team is to wri te a program that plays Krypto. Input will be a series of hands,
one per 80 column line. Each line will contain the five cards in the hand and the face-up
card separated by one or more spaces. The program should print a solution for each hand in
the left-to-right format described above (use * for multiplication and / for division). If
no solution can be found, produce a message to that effect and go on to the next hand.

The example below shows how the output should look.

Samples:

INPUT OUTPUT

15 9 4 3 II 5 15 + II - 9 + 3 / 4 = 5
1 2 1 1 2 25 1 211 2 CANNOT BE COMBINED TO EQUAL 25

2
Name: Fizz-Buzz USSC85 - 3

Files:
program fizz.pas
input fizz.in
output fizz.out

Task:

Fizz-Buzz is a party game played by 2 to 12 people. The game starts when the first
player calls aut "1". The second player calls aut "2", and play continues in a circle.

Players are to call aut the natural numbers in sequence according to some special
rules:

If number is a multiple of 3 or contains the digit 3, it is a fizz.


If a number is a multiple of 7 or contains the digit 7, it is a buzz.
If a number is both a fizz and a buzz, it is a fizz-buzz.

Numbers which are one of the above must be called aut wi th the appropriate word
instead of the number. If a player is caught making an error, (slhe is eliminated. The last
player remaining is the winner.
You are to write a program that prints Fizz-Buzz tables. input to your program will be
a list of number pairs. Each pair will consist of the number of columns (corresponding to
the number of players, 2 to 12) in the table and the minimum number to be processed, on one
line separated by spaces. For each table you should eject a page, print a header, and print
the sequence up to the specified maximum using the proper number of columns. Use a format
similar to the example shown.

Samples:

INPUT OUTPUT

3 10 THE FIZZBUZZ SEQUENCE TO 10:


10 30
1 2 FIZZ
4 5 FIZZ
BUZZ 8 FIZZ
10

- new page -

THE FIZZBUZZ SEQUENCE TO 30:

1 2 FIZZ 4 5 FIZZ BUZZ 8 FIZZ 10


II FIZZ FIZZ BUZZ FIZZ 16 BUZZ FIZZ 19 20
FIZZBUZZ 22 Frzz FIZZ 25 26 FIZZBUZZ BUZZ 29 Frzz

3
Name: Asteroids! USSC85 - 4

Files:
program roids.pas
input roids.in
output roids.out

Task:

Vapor Video is producing a new game in which the player defends the earth against an
asteroid swarm with a variety of missiles which can fragment or deflect them. The task of
your team is to wri te the program which calculates the res ul ts of each atta ck . It is
sufficient to consider each asteroid in isolation in an earth centered coordinate system.
See figure 1.
The combination of the asteroid speed and the time the player has to attack is such
that the distance the asteroid is deflected is a linear function of
its 2-velocity and the
time remaining until its y coordinate is O. abs(x) must be >= 6.3 x 10A6 meters at that time
in order to miss be earth. For example, if the asteroid has an x-velocity of -7.4meters/sec
after an atta ck at 10.2 days before impact, it will have x = 6.52 x 10A6 meters when y = O
and will miss the earth. If the asteroid is fragmented by the attack, it will no longer be a
threat. Note that the missile will always hit the proper point on the asteroid so that it
will not ch ange the asteroid's y-velocity.
Higher level routines will keep track of the asteroids. You only have to look at the
effect of each shot. The asteroids will always be close enough to the positi ve y-axis so
that you only have to consider the x-ve loci ty. You wi II be gi ven the time to impact r the
radius of the asteroid, the missile aim point, the warhead size, and the initial x-velocity.
You need to return the depth of the fracture zone caused by the missile (see figure 2), the
new x-velocity, and the state of the asteroid: whether it is fragmented or if it will hit or
miss the earth with no further attacks.
The asteroids are a Ll rock spheres with a density of 3.5 x 10A6 grams/meterA3. The
following information from "The Asteroid Miner's Handbook" is alI that is needed.
Symbols:
S:Radius of asteroid in meters
M:Mass of asteroid in grams
W:Size of missile warhead in megaton equivalents of TNT
R:Radius of crater in meters
D:Depth of crater in meters
F:Depth of fracture zone in meters
V:Volume of crater in cubic meters
dV:Change in velocity in meters/sec

M = 1.47 x 10A7SA3
R=94 .5$WO. 28
D=0.500R
F=0.750R
V =pi/2*RA2*D
dV=(1.17*10A9*V)/M
if F>0.855 the asteroid is fragmented.

The input will be a sequence of lines, one line per test case, terminated by end of
file. Each line has four numbers: the time in days before the asteroid crosses y = O, the
radius of the asteroid in meters, the size of the missile warhead in megaton equivalents of
TNT, and the initial x-velocity in meters/sec.
The aim point follows: a '+' indicates the hit will be on the left side (in figure 1)
and yield a positive increment in the x-velocity, while a '-' indicates a hit on the right
side which will yield a negative increment (the single quotes are literaily included in the
input). The fields are separated by at least one blank. Each line is less than 81 characters

4
in length. The numbers consist of an integer part and an optional decimal point and fraction
part.
The output for each case must be a formatted listing of the input followed by the
resul ts of your calculation: the depth of the fracture zone in meters, the new x-veloci ty
and the status of the asteroid leither "fragmented", "hit" or "miss"). The numbers should
be accurate to three places and can be either fixed or floating format with a sign if
required. Skip at least one line between cases. The exact format is not important as long as
the numbers are correct and the layout is understandable.

Samples:

INPUT OUTPUT

10.2 698. 100 O. '- , TIME TO IMPACT: 10.2 DAYS


15 5000 1000 .1 ,+, RADIUS OF ASTEROID: 698 METERS
2.5 30 .03 O ,+, SIZE OF WARHEAD 100 . MEGATONSINITIAL
X-VELOCITY: O. METERS/SEC
AlM: -
FRACTURE RADIUS 257. METSRS
FINAL X-VSLOCITY: -7.42 MSTSR/SSC
STATUS: MISS

TIMS TO IMPACT: 15.0 DAYS


RADIUS OF ASTSROID: 5000 METERS
SIZE OF WARHEAD; 1000 MSGATONS
INITIAL X-VSLOCITY: 0.1 METSRS/SSC
AlM: +
FRACTURS RADIUS 490. METERS
FINAL X-YELOCITY: 0.24 MSTSRS/SSC
STATUS: HIT

TIME TO IMPACT : 2.5 DAYS


RADIUS OF ASTSROID : 30.0 MSTERS
SI ZS OF WARHSAD: 03 MSGATONS
INITIAL X-YSLOCITY: O METSRS/SSC
AlM : +
FRACTURS RADIUS: 26.6 MSTERS
FINAL. VELOCITY : 103. MSTSRS/SEC
STATUS: FRAGMSNTSD

Name: Jigsaw Puzzle USSC85 - 5

Files:
program jigsaw.pas
input jigsaw.in
output jigsaw.out

Task:

Four identically shaped pieces are to be fit into varying shapes without overlaps or
gaps (see figure 1). Each piece is composed of three unit squares shaped like an L. In the
Cartesian coordinate system, a piece could be described by the set of pairs
{ ll, 1), 12, 1), ll, 2) }

5
Each point represents a square centered at that point. Each piece may be rotated or
translated as required to St it into the puzzle.
Input will consist of several shapes to be fitted. Each line of input will represent
one shape. Each shape is described by 12 pairs of positive integer coordinates. The shape
consists of 12 squares centered at each input point. There are no special separators between
the pairs. A line of input will thus contain 24 blank separated integers consisting of 12
consecutive (z, y) coordinate pairs. Each input integer, 1, satisfies 1<=1<=40.

For each shape, a separator is to be output identifying the shape number. If the
pieces can be fit into the shape, a "picture" is to be produced of any solution showing the
location of each piece within the shape.
Use 40 lines of output to draw the picture. Each character position on an output line
will correspond to one square in the shape. Line 1 represents the points
(1,40),(2,40), ... ,(40,40). The last line contains (1, 1), (2,1), (40,1). Place each
picture on a separate page.
The output at (x, y) should be a blank if this square is not in the input shape, or
the digit i if piece i covers that square. Assume the pieces are numbered 1 to 4.
Figure 2 illustrates the shape defined by the second line of sample input.
Figure 3 shows one possible solution for this input. This solution is shown in the
required printed form in the sample output section .

• ~:I I•... : +.'.··I·.···:···I····:····l····:···1···:

: 3 ... -fo- ...1...:.1 ·:·+··:····1···: 1····:


'2
. ·.·.:---,I····:···I····j.···:·I ....
:
1 I

o ... J .~. 3 .. :4: .i!5.. ....

1· .....

:..~

3 1·:····1········1················1····.··· ..3 ..

:2 ....L-I- ···1···,··· .... r-I- ···1·····,····

o .....,...:1 1····.:~
•··• . 3 .....:.4"
1'·"'·1···· .:····1·····,

Samples:

INPUT OUTPUT

1 1 2 1 3 1 4 1 1 2 2 2 3 2 4 2 1 3 2 3 3 3 4 3 SOLUTION FOR SHAPE 1


2 1 3 1 1 2 2 2 3 2 4 2 1 3 2 3 3 3 4 3 2 4 3 4 - 97 blank lines -
1 1 2 1 3 1 1 2 2 2 3 2 1 3 2 3 3 3 4 3 1 4 2 4 2233
1243
1144
- new page -
SOLUTION FOR SHAPE 2
- 96 blank lines-
33
2234
2144
II
- new page -
THERE IS NO SOLUTION FOR SHAPE 3

6
Name: Transmitter Hunting USSC85 - 6

Files:
program trans.pas
input trans. in
output trans.out

Task:

A common pastime among amateur radio (ham) operators is transmitter finding (T-
hunting). This can best be described as hide-and-seek by radio. The hider finds some nice
spot and starts transmitting. The lookers start by taking readings with directional antennas
from various locations. They then attempt to find the hider by driving to the position where
the ini ti al readings tend to intersect and-use mobile equipment to home in on the radio
signal.
In an attempt to increase your hunting efficiency you have decided to write a program
that will process the initial readings and list the locations where the readings intersect.
The area to be considered will be broken up into a 1000 by 1000 grid, with corners at (0,0),
(0,1000), (1000,1000), and (1000,0). You will read sets of three readings and print a report
containing ali intersections which are within the grid.
Input will consist of sets of readings terminated by the end-of file. Each set will
consist of three readings, with each reading on a separate 80column line. A reading will
consist of the 2 coordinate and the y coordinate of the location the reading was taken from
along with the heading in whole degrees (O = north, 90 = east, 180 = south, 270 = west). The
elements of a reading are separated by one or more spaces.
The program must print a report for each set of readings containing the ini ti al
readings and the intersections within the 1000 by 1000 grid. Intersections may be either
points or line segments. Your report should list each point intersection by its (x,y)
coordinates and each line segment intersection by the coordinates of the endpoints. If no
intersections exist, produce a message to that effect. No intersection should appear more
than once.
Each report should be printed on a separate page. Use a format similar to the example
below.

Samples:

INPUT OUTPUT

100 100 O (100,100) O DEGREES


100 600 180 (100,600) 180 DEGREES
200 350 27 O (100,350) 270 DEGREES

INTERSECTIONS:
POINT AT (100,350)
LINE SEGMENT BETWEEN (100,100) AND (100,600)

7
Name: lefedés KlTE91 1

Files:
program a.pas
input a.inp
output a.out

Task:

A számegyenesen N számpárral N szakaszt határozunk meg, amely lefedi a számegyenes


megfelelo részeit.

Az INPUT file:
Tartalmazhat több lefedés leírását is. Egy lefedést úgy adunk meg, hogy soronként
megadjuk alefedo intervallumok kezdo és végpontjait. Az egyes lefedések megadását '*'
választja el egymástól.

Az OUTPUT file:
Megadja adott sorban, hogya lefedés mekkora részt takar a számegyenesen.

Samples:

INPUT OUTPUT

-2 5 10
7 9 3
8 10
*
1 3

4 5

Name: Kocka KlTE91 2

Files:
program b.pas
input b.inp
output b.out

Task:

Egy N (N egész) élhosszúságú kockát feldarabolunk 1 élhosszúságú kis kockákra. Ezután


a nagy kockából kiveszünk meghatározott számú kis kockát.

Az INPUT file:
Tartalmazhat több kocka leírást is. Egy kockát úgy adunk meg, hogy az elso sorban
megadjuk a kocka élhosszúságát, majd ezt követo en soronként a hiányzó kis kockák
koordinátáit (kezdöpontnak valamelyik csúcspontot válasszuk, s az ebbol kiinduló három élre
illeszkedo tengelyeken l-tol N-ig számozzunk meg 1 egység hosszúságú rekeszeket, így minden
kis kockát egy számhármas határoz meg.). Az egyes kockák megadását '* , zárja le.

Az OUTPUT file:
Megadja az így keletkezett test(ek) külso felszínét, azaz a belso zárt üregek
felszínét, amelyeket kívülröl nem tudunk elérni nem kell figyelembe venni.

8
Samples:

INPUT OUTPUT

4 96
2 2 2 8
2 2 3
2 3 2
2 3 3
3 2 2
3 2 3
3 3 2
*

1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1

Name: taxman KLTE91 3

Files:
program c.pas
input c.inp
output c.out

Task:

Tekintsük a következokben meghatározott játékot.

1./ A játék tárgya az 1, ... ,N számhalmaz (N input adat).

2./ A játékos kivehet a számhalmazból egy olyan számot, amelynek valamely osztója is
megtalálható a halmazban.

3./ A szám kiválasztása után a játékvezetönek (gépnek) ki kell vennie a halmazból a


játékos által kiválasztott szám valamennyi halmazban levo osztóját, és a játékos
pontszámát meg kell növeIni a játékos által kiválasztott szám értékével.

4./ Ha még van kiveheto szám a halmazban, akkor a 2./ pontnál folytatható a játék. A
játék célja, hogya játékos a leheto legtöbb pontot szerezze.

Az INPUT file:
A kiindulásuI vett számokat tartalmazza soronként.

Az OUTPUT file:
Tartalmazza a maximális pontszámot, valamint azt, hogy mely számokat és milyen
sorrendben kell a játékosnak kiválasztania, hogya leheto legtöbb pontot szerezze, valamint
az egyes kiválasztott számoknál a gép melyik osztókat veszi ki.

9
Samples:

INPUT OUTPUT

8 Max. pont: 21
II A kiválasztott számok és osztói:
7 : 1

6 : 2 3
8 : 4
Max. pont: 14
A kiválasztott számok és osztói:
II : 1

9 : 3

6 : 2
8 : 4
10 : 5

Name: Út KLTE91 4

Files:
program d.pas
input d.inp
output d.out

Task:

A kör alakú A ország középpontja legyen a (0,0) pont. Az A ország körül helyezkedik el
a B ország. 8gy vállalatnak van mindkét országban egy-egy gyáregysége. Az A ország közutjain
max. 100 km/h sebességgel, míg a B országban max. 80 km/h sebességgel lehet közlekedni. Az A
ország sugara 150 km.

Az INPUT file:
Több esetet is tartalmazhat, az egyes eseteket '* , választj a el egymástól. Az egyes
esetek leírásában az elso sorban tartalmazza az A országbeli gyár koordinátáit, a második
sorban pedig a B országban levoét.

Az OUTPUT file:
Tartalmazza a két gyár között annak az útnak a hosszát, melyen a legrövidebb ido alatt
tudunk az egyik gyárból a másikba eljutni.

Samples:

[INPUT [ OUTPUT

50 50 155.73 krn
10 200

10
Name: Szint KLTE91 5

Files:
program e.pas
input e.inp
output e.out

Task:

Egy téglalap alakú tartományt felbontottunk adott s r s qű


ű ű é rácsra, és megmértük a
tartományt lefedo felületnek a rácspontokban elért magasságát (ez egy pozitív egész).
Mondjuk meg, körbe lehet-e járni adott magasság intervallumban a legmagasabb csúcsot, azaz
tudunk-e rácspont ról szomszédos rácspontra lépkedve önmagába v i ss za t r é ö utat bej árni úgy,
hogy az érintett rácspontokban felvett érték (x) a megadott alsóhatár és f e l.s öh a t r
á közé
essen, (ah i x i fh; ah, fh pozití v egés z), és a maximális értéket fel vevo egyik rácspont a
körön belül legyen! Szomszédos rácspontoknak tekintjük az átlós szomszédokat is. A keresett
kör nem haladhat át az általa körbezárt maximális értéku rácsponton.

Az INPUT file:
Tartalmazhat több felUlet leírást is, melyeket egy-egy '* '-ot tartalmazó sor zár le.
Egy felületet úgy írunk le, hogy az elso sorban megadjuk az intervallum alsó- és
felsohatárát, a második sorban a tartomány méretét (a rács sorainak és oszlopainak számát),
majd ezek után soronként a rácspontokban mért értékeket. Az egy sorban levo egész számokat
egy-egy szóköz választja el.

Az OUTPUT file
Pontosan annyi sort tartalmazzon, ahány felUlet leírása szerepelt az input file-ban.
Minden sor a "KÖRBEJÁRHATÓ" illetve a "NEM JÁRHATÓ KÖRBE" Uzenetek valamelyikét tartalmazza
annak megfeleloen, hogy kérdéses felületen rajzolható-e szintvonal vagy sem.

Samples:

INPUT OUTPUT

3 5 KÖRBEJÁRHATÓ
3 3 NEM JÁRHATÓ KÖRBE
5 4 3
3 6 3
4 4 4
*
3 5
4 5
4 4 4 4 4
4 5 5 5 5
4 6 7 6 5
4 3 2 4 1

II
Name: matrix KLTE91 6

Files:
program f.pas
input f.inp
output f.out

Task:

Ha lehet rendezd át úgy egy egész számokat tartalmazó négyzetes mátrix sorait, hogy
az átalakítás után keletkezett mátrix föátlójába került elemek a kisebb indexuektöl a
nagyobbak felé nagyság szerint monoton növekedj enek! (Fontos! A rendezés során csak telj es
sorokat lehet mozgatni! )

Az INPUT file
Normál szövegfile, melyben akár több mátrix is le lehet írva. Egy tömb leírása a
következö szerkezetu:

n
a(l,l) a(I,2) a(l,n)
a(2,1) a(2,2) a(2,n)

a(n,l) a(n,2) a(n,n)

Jelölések: n - a mátrix sorainak száma /O<n<~10/, a(i,j) - a mátrix i. sorának j.


eleme.

Ha több mátrix is van a file-ban, akkor azok minden különösebb elválasztás nélkül
követik egymást.

Az OUTPUTfile
Ha a megadott mátrix nem rendezhetö, akkor az output file-ban az eredmény mátrix
helyett egy sorban az szerepeljen, hogy: Nem rendezhetö

Samples:

INPUT OUTPUT

2 2 1
2 1 1 2
1 2
3 123
1 2 3 17 5 7
486 486
17 5 7

12
Name: GRAF KlTE91 7

Files:
program g.pas
input g.inp
output g.out

Task:

Egy gráfról mondjuk meg program segítségével, hogy minimum hány szín kell ahhoz, hogy
a szomszédos csúcsait különbözo színure festve a teljes gráfot beszinezzük!

Az INPUT file:
A gráf az élek felsorolásával van megadva. Két gráfot egy '* , választ el egymástól.
Egy-egy gráf megadásakor e Lö s z r
ö az élek száma található, majd az élek felsorolása jön
(egyik csúcs, szóköz, másik csúcs, soremelés).

Az OUTPUT file:
Az egyes gráfokhoz tartozó minimális színszám.

Samples:

INPUT OUTPUT

3 3
1 2 2
2 3
3 1
*
4
1 2
1 3
3 4
5 1

Name: Playcard IOAG91

Files:
program playcard.pas
input playcard.inp
output playcard.out

Task:

A pack of cards consists of 52 cards, which have 13 different values


1,2,3,4,5,6,7,B,9,10,J,Q,K, and four different suits: Spades, Clubs, Diamonds, Hearts (Spade
and Club are black, Diamonds and Hearts are red). We have a pack of full cards, which we
shuffle. Pulling out successively 12 cards of the pack we create 3 rows of 4 cards each,
which we place on the table.

If, in that phase, we puli out a J, Q or K we put that card at the end of the pack and
continue pulling out cards until 3 rows of 4 cards each are completed. We now proceed
checking if among the cards, we have put on the table, there are pairs of cards whose values

13
give 10 as sum. If there are two cards with the value of 10 each, one of them is considered
as having value o. On the above pairs of cards we place two cards of the pack one on each
card of the pair ). If during this phase we pulI out a J, Q or K we place this on one card
of the pair and this card does not take part in the procedure any more.

The procedure continues until the 12 faces of the cards are covered by J,Q,K or there
are no more pairs of cards with sum 10. Write a program which simulates the above procedure
with the following demands:

1. - The number N of repeti tions of the above procedure must be entered from the
keyboard. When Nequals 1, each of 2,3 and 4 below takes place.

2. - (a) The pack of cards must be created and, for each repetition the pack of cards
must be shuffled by the program.

(b) The pack of cards must be displayed on the screen.

3. (a) The 12 cards must be placed on the screen according to the procedure
described above.

(b) The remaining cards in the pack must be displayed on the screen.

4. - (a) The cards that are covered according to the above procedure must be replaced
with the cards that replace them and this must be shown on the display.

(b) After each replacement, the remaining cards of the pack must be displayed on
the screen.

5. - After 5 repetitions, a histogram must be presented which will display the number
of cards which remain in the pack after the end of each procedure.

Name: Trees IOAG91 2

Files:
program trees.pas
input trees.inp
output trees.out

Task:

A farmer wants to preserve a ra re class of ancient cypress trees. In order to do that


he has taken note of the position of each tree and he has decided to surround the trees with
wire drawing a polygon such that they lie entirely inside it. In order to reduce his costs,
he needs to minimize the length of wire. The farmer wants to build a rectangular house, one
of its sides being parallel to the X-axis, and he needs to know the relative location of the
house:
(1) The house is outside the polygon.
(2) The house is inside the polygon.
(3) The wire divides the house in two regions whose areas are different from zero.
Write a program capable of accomplishing the following tasks:
(A) Finds the trees that will be the vertices of the polygon.
(B) Calculates the length of wire that will be used.
(C) Indicates in which of the above mentioned locations (1,2,3) the farmer's house
is.

Input:

14
- N: The number of the trees.
- (Xi,Yi) l<=i<=N, N<=20, Xi,Yi>O; The coordinates of the points corresponding to
each tree.
- (a,b), (c,d), a,b,c,d>O; The beginning and ending points of the house's main
diagonal.

Output:
- A sequence of M points (l<=M<=N) with the property that if we trace through the
points in the order in which they appear, we trace the outline of the polygon.
- The length of wire that will be used.
- The indication of the position of the house in the form "1","2", or "3"

Name: Square IOAG91 3

Files:
program square.pas
input square.inp
output square.out

Task:

Enumerate the position of a 5x5 matrix, in the following way: If the number i
(1<=i<=25) has be en assigned to a matrix position with coordinates (x,y), then the number
i+ 1 can be assigned to the matrix posi tion wi th coordinates (z,w) according to one of the
following rules:
(1) (z,w) (x+-3,y)
(2) (z,w) (x,y+-3)
(3) (z,w) (x+-2,y+-2)

The problem is:


(A) Write a program that enumerates the positions of
the 5x5 matrix for agiven starting position with the
number 1.

(B) Compute the number of all possible enumerations for every starting position at
the upper right part of the matrix, including the main diagonal.

8xample:
If the matrix position with coordinates (2,2) is selected as the starting position,
then the next matrix position to which number 2 will be assigned, can be one of the
following positions with coordinates: (2,5) or (5,2) or (4,4). These positions are marked in
figure 1 by an asterisk (*).

1 2 3 4 5
+---+---+---+---+---+
1

+---+---+---+---+---+
2 : 1 : : * :
+---+---+---+---+---+
3
+---+---+---+---+---+
: * :
+---+---+---+---+---+
5 : * :
+---+---+---+---+---+

15
Note:
It will be appreciated if the output looks like the one in figure 1.

Name: Maximum Gang IOAG91 4

Files:
program gang.pas
input gang.inp
output gang.out

Task:

A Police captain knows we Ll. a lL the outlaw persons of his city, as we lI as, every
possible collaboration among them. He would like to find the maximum gang of the city. In
this case, a gang is a subset of outlaw persons so that any person in it collaborates with
a Ll. others in the subset . Maximum gang means that there does not exist another gang wi th
great er cardinality.

Create a program capable of carrying out the following tasks:


(A) Accept the police captain's data with a total
number of outlaw persons less than 41. Use as
input data file an ASCII one with the following
structure:
a (1,1)
a(2,1)a(2,2)
a(3,1)a(3,2)a(3,3)

a(n,1)a(n,2)a(n,3) a(n,n)
where a(i,j)=l, if person i is collaborating with
person j or i=j, and a(i,j)=O, otherwise. for
instance (in the case of 6 persons):
1

01
101
1011
01101
101111
In this example an output can be the following
one:

A Maximum Gang is
136
cardinality = 4
(B) Extend the input part of the program, so that to
generate data in a random way under agiven pro-
pability O < d < 1 of collaboration of outlaw
persons.
(C) Using random data or input file, find the maximum
gang of the city.
Use the same output format as in the example
above ( see task A ).

16
Name: Let's Go To The TUBP91 1
Movies

Files:
program p1.pas
input p1.inp
output p1.out

Task:

There is a very small cinema in the town -- with only 30 seats where once a day,
late night a good artistic or occasionally erotic film can be seen. The place is a bit
shabby, far from the busy centre, so the tickets are fairly cheap 50 Ft each, otherwise
nobody would go there.
Due to security reasons the cash-box is always empty when the ticket office opens.
Visitors are expected to have either a 50 or a 100 Ft bank note. They arrive one-by-one, and
the cashier can se11 them a ticket only if they either pay with a 50 Ft bill, or she can
give back the proper change, i.e. if she has at least one 50 Ft bill in the cash-box exactly
when it is needed. If she can't give back the money, she gets really embarrassed, closes the
office and runs home, so that the film for the night will be cancelled.
Suppose that the number of the expected visitors is known in advance but they arrive
randomly. Now, write a program to determine the number of all possible sequences of persons
(or their banknotes), arriving at the cash-box, such that everybody can buy a ticket.
The input to the program is in a file, called Pl. INP, where each line contains one
positive number indicating the number of the would-be audience for the film. The output
file, PI.OUT, shou1d contain the corresponding answers the number of the possible
sequences -- as integer numbers, one on each line. The input number will not exceed the
capa city of the cinema.

Samples:

INPUT OUTPUT

5 10
2 2
12 924

Name: Maximal TUBP91 2


Subsequence

Files:
program p2.pas
input p2.inp
output p2.out

Task:

There is a sequence. of integer -- positive and negative numbers. Your task is to


wri te a program which finds a continuous subsequence where the sum of the integers is
maxirnal.
The input to the program is in a file, called P2.INP, where each line contains
positive or negative integers, separated by single spaces. A sequence can span several

17
lines, and it is terminated with the number zero. In the file there may be several of such
sequences. The output file, P2.0UT, must contain one line for each of the input sequences,
where the largest sum of any continuous sequence is printed . The longest sequence in the
input file can contain up to 250 numbers.

Samples:

INPUT OUTPUT

1 -2 1 3 5
-1 2 O 6
1 3 2 O

Name: Best Almighty Date TUBP91 3


Scribbler

Files:
program p3.pas
input p3.inp
output p3.out

Task:

Big Bubbles Unlimited, a polynational company, sends hundreds of letters a day to


every corner in the world. Ms Pedant, the recent1y appointed Chief Public Relationist at its
new Balmazujvaros-based headquarters, has soon discovered the diversity of date formats the
correspondents use in their letters. (However, they never mix the various date formats
within one letter.) As she finds it an offence against the company's appearance, she charges
you with the task of writing the Best Almighty Date Scribbler (briefly, BADS) in Pascal. The
program is supposed to
1) read a tagged date conversion rule (first line), and the name of the source
and destination files (second line) from a textfile called P3.INP,
2) read a line of text from the source file (a textfile),
3) convert any date that matches the left side of the rule into the format given
on the right side, and then write the modified line into the destination file
(a new textfile),
4) continue with step 2 until end of source file is encountered,
5) continue with step 1 until end of file is found.

The syntax of the tagged date conversion rules is as follows (terminal symbols are
'single quoted'):
rule: 'leftSide'=>'rightSide'.
leftSide: tag, item, separator, item, separator, item.
rightSide: leftSide.
tag: 'YMO'; 'MOY'; 'OMY'.
item: year; month; day.
year: 'dd' ; 'dddd' .
month: 'dd' ; I aaa 1.

day: ld' ; 'dd' .


separator: '/ ' ;

'YMO', 'MOY' and 'OMY' (where Y = year, M = month, O = day) describe the order in
which the three items of a date are to be interpreted. Input line length is limited to 80
characters. AlI dates refer to the 20th century.

18
At both sides of a date conversion rule, each 'd' matches a digi t from O to 9, and
each 'a' matches a letter from A to Z, or a to z (English alphabet). The program doesn't
have to check the validity of days and years, nor the syntax of the rules. However, it may
have to convert a month's number to its three character name (Jan, Feb, Mar, Apr, May, Jun,
Jul, Aug, Sep, Oct, Nov, Dec), or vice versa.

Samples:

INPUT OUTPUT

P3.INP

YMDdd/dd/dd~>MDYaaa/dd/dd
Ernest
DMYdd/dd/dddd~>YMDdd-aaa-dd
Judy
ERNEST.INP ERNEST.OUT

To Ernest Lonely, Old Harbour To Ernest Lonely, Old Harbour


New Harbour, 91/10/04 New Harbour, Oct/4/91
Ref. 05/10-31/1991 Ref. 05/10-31/1991
Earnest, Earnest,
I want to see you immediately!! Call me, please, not I want to see you immediately!! Call me, please, not
later than later than
91/10/10!! I have an urgent matter to discuss with Oct/10/91!! 1 have an urgent matter to discuss with
you you
concerning our holiday between 91/12/28 and 92/01/03. concerning our holiday between Dec/28/91 and
1 canlt go Jan/03/92. 1 can't go
for I'll start my new job with New World just after for 1'11 start my new job with New World just after
Xmas, on 91/12/27. Xmas, on Dec/27/91.
Regards, Regards,
Geyza Geyza
JUDY.INP JUDY.OUT

To Judy Lovely, Fifth World To Judy Lovely, Fifth World


Nocity, 04/10/1991 Nocity, 91-0ct-04
Ref. 05/10-31/1991 Ref. 05/10-31/1991
Hi Judy, Hi Judy,
call me, please, on 10/10/1991. 1 have an urgent call me, please, on 91-0ct-lD. 1 have an urgent
business matter business matter
concerning our conference between 17/01/1992 and concerning our conference between 92-Jan-17 and 92-
21/01/1992. Or Jan-21. Or
may 1 see you on 12/10/1991 during my visit to Fifth may 1 see you on 91-0ct-12 during my visit to Fifth
World? World?
With love, With love,
Geyza Geyza

Name: Minimal Difference TUBP91 3

Files:
program p3.pas
input p3.inp
output p3.out

Task:

There is a decimal number containing 2n digi ts. You have to form two numbers, each
containing exactly n digits from the originalone, in such a way that the difference of the
two newly forrned number be minimal. Each digit of the original number should be used only
once.
The input file, P4. INP, contains the original numbers, one in a line. The resul t
should be written into a file called P4.0UT, every line containing the two resulting numbers
and their difference, separated by spaces.

19
Samples:

INPUT OUTPUT

63960804 6400 6398 2


4159 51 49 2

Name: Pocket Calculator TUBP91 5

Files:
program p5.pas
input p5.inp
output p5.out

Task:

Abacus Inc., the market leader manufacturer of pocket ca1cu1ators is planning to


develop a new model, which is able to work with mathematical formulae, consisting of
variables, numeric constants, and operators. A variable can be assigned a value according
the following syntactic rules:
<assignment> : :=<variable><separator>":="<separator><expression>
<expr> ::= <variable>1 <constant>1
<expr><separator><operator><separator><expr>I
" ("<separator><expression><separator>" I"
<variable> <letter>1 <variable><letter>
<constant> <integer>1 <real>
<integer> ::= <digit>1 <integer><digit>
<real> ::= <integer>". "<integer>
<digit> ::= "O" I "1" 1"2" 1"3" I "4" I "5" 1"6" I "7" I "8" I "9"
<letter> ::= "A" I "B" I "C" I"D" I "E" I "F" I "G" I "H"
<separator> ::= ""1" '1 <separator>
<operator> ::= "+111"_"1"*"1"/"

The length of variable names and numeric constants, the nesting level of parentheses
are not limited by the grammar.
You, a young and gi fted employee of Abacus, are charged wi th wri ting the syntax
checker of the new calculator. Your Pascal program should be able to check whether a formula
satisfies the syntactic rules given above.
The program reads its data from a file, P5.INP, each line containing a formula, and
should produce an output file, P5.0UT, where each line contains the word PASSED or REJECTED,
depending on the resul t of the syntax check. The program does not have to calculate the
result of the formulae.
Samples:

INPUT OUTPUT

H:=(A-BI*(AtBI PASSED
0:=( ( A I + (B * C * Ol I PASSEO
H:=( (A-BI*(AtBI REJECTED

20
Name: Seven Up TUBP91 6

Files:
program p6.pas
input p6.inp
output p6.out

Task:

The subcommittee Seven Lean Years keeps its proposal, as top secret, under seven seals. Its
members simply call it the Seven at One Stroke law. Now, they urgently need your help.
Stop reading here if you can not keep secrets!
The cardinal part of the proposal says all acute problems of the Hungarian economy, being at
its sixes and sevens, could be easily solved by reintroducing the ancient Hungarian septal
(i.e. base 7) number system for the number seven has, as generally known, a magic effect.
Further, the majority of the subcommittee stands up for a non-place-valued number repre-
sentation claiming that then all numbers are longer and, consequently, wages seem to be
higher. (The opposition is, of course, wrong by saying that in that case also the prices
look higher. )
The proposal assigns the names of the seven Hungarian home-conquering chieftains to the
digits of the new-old number system. Each of the seven so-called lean digits is denoted by a
characteristic letter of these names (see below. Their outdated decimal equivalents are also
given in parentheses) .
Álmos (A = 1) , Elöd (E 4) r
Ond (O 7) , Kont (K 4*7) r
Tas (T 72) , Huba (H 4*72) ,
Töhötöm (M = 73)

Examples of the first fifty six lean numbers are shown in the table below:

+1 +2 +3 +4 +5 +6 +7
O A AA AE EOA EOAA AO O
7 OA OAA OAE OEOA OEOAA OAO 00
14 OOA OOAA OOAE OOEOA OOEOAA OOAO OK
21 OKA OKAA EK EKA EKAA AK KTO
28 KT OA KTOAA KTOAE KTOEOA KTOEOAA KTOAO KTOO
35 KTOOA KTOOAA KTOOAE KTOOEOA TOOEOAA KTOOAO OT
42 OTA OTAA ET ETA ETAA AT T
49 TA TAA TAE TEOA TEOAA TAO TO

The rules for generating or accepting lean numbers are the following.
Digits of a lean number are to be written from left to right in decreasing order except that
a lean digit may immediately be preceded by one smaller lean digit. No more than two lean
digits of equal value may follow one another. A lean digit placed before a lean digit of
greater value subtracts. A lean digit placed after a lean digit of greater or equal value
adds.
According to these rules lean numbers can have alternative forms. E.g. AE can be written as
EO, OA as EE, EOA as E, OK as KT, EK as OKAE, or ET as OTAE, etc.
Your task:
Write a program to evaluate additions and subtractions in the lean-number notation. The
operators + (add) and - (subtract) are allowed, and no parenthesis can be used. Lean
expressions, terminated by the end of line, should be read from a file called P6.INP, and
evaluated from left to right. The results (see the examples below for proper formatting)
should be written into another file called P6.0UT. Space and tab characters in the input
should be ignored. The program also has to check the syntactic validity of the lean numbers.
Any error, including lean number overflow, should be flagged.

21
Samples:

INPUT OUTPUT

A +AA 3 = AE
AE + AE 6 = AO
EO - EO Lean expr aut of range
AM - A 341 = EMAA
MM 686 = MM
TTKA - K 99 = TTA
A 1 = A
AA 2 = AA

AAE Wrong lean expr! Rest: E


MMMHHHT Wrong lean expr! Rest: MHHHT

Name: Papering Our Home TUBP91 7

Files:
program p7.pas
input p7.inp
output p7.out

Task:

We would like to cover our walls with nice, trendy wallpaper, but such papers cost a
lot, so we pre fer to minimize the costs, i.e. the number of rolls we have to use.
You may cut the wallpaper with restrictions: either across the paper, or lengthwise.
However, no cut is allowed to appear horizontally, in the mid of a wall. Two strips of
walipaper may be joined only lengthwise (verticaily), no overlap is necessary. The wallpaper
pieces may be used later in their whole, or cut according to the rules above.
Let's take a computer and write a program to find the minimal number of rolls. In the
input file, P7.INP,

the first line gives the length and width of a walipaper roll (all rolls are
identical),
the next lines describe the length and width of rectangular areas to be
covered (one area by one line),
the lines describing a room are terminated by a line containing zero,
more lines describing more rooms may follow, up to the end of the file
(different wallpapers are used for different rooms).

The lines of the output file, P7.0UT, should contain the number of the rolls to be
bought.

Samples:

INPUT OUTPUT

10 0.5 5
2.5 10 5
O
0.8 1.5
2.3 10
0.7 0.5
O

22
Name: Joker RUGB91 1

Files:
program joker.pas
input joker.in
output joker.out

Task:

Write a program that is able to compute the amount of money you have won with agiven
winning Joker number. You ate gi ven the winning Joker number and a list of numbers that
should be checked to find out how much they have won. All numbers contain 7 digits. When two
or more successive digits correspond to the winning Joker number and if they are in the same
position as in the winning Joker number, you win 80 SF or more. The amount you win depends
on the number of successive digits which correspond with the Joker number, according to the
following table:

o O
1 O
2 80

3800
4 8000
5 80000
6 800000
7 8000000

For example: the winning Joker number is 7254780; the number to check is 4253900. Only
2,5 and O are digits which correspond with the winning Joker number (4 is not in the right
position) . Since only 2 and 5 are successive digits, you win 80 SF.
The input file contains the winning joker number on it' s first line, and then a list
of numbers to check, each on separate lines. The output file contains the number to check,
followed by two blanks and the amount of money the number won. The input file is error-free.

Samples:

INPUT OUTPUT

1234567 1253467 160


1253467 0123456 O
0123456 3234578 8000
3234578 1244569 880
1244569

Name: Calc RUGB91 2

Files:
program calc.pas
input calc1.in ... calc10.i
n
output calc.out

23
Task:

The main purpose of this highly ingenious CALC-program you are about to write, is
(general constertation!) to calculate. You will have to produce some results, based on not
terribly complicated mathematical formulae, contained in a file. The file does not provide
you with ready-to-use numbers, but with numbers written out as ASClI-words instead, e.g. one
+ two. Unfortunately, 1 dropped my floppy-disk and the characters got mixed up. What 1 am
actually trying to say is that the file is in code !
Your mission, should you choose to accept it (this line is stolen from the American
TVseries Mission Impossible, but do not let this upset you!), is to give me the results of
those formulae. Should you, or any of your crew be killed during this action, the Government
will disavow any responsibility (Mission Impossible again).
Let us get down to business now. AlI the 1/0 the program has to do is to

-read its input from 10 test files CALC1.IN to CALC10.DV


-write the result of the formulae to the file CALC.OUT (one line per input file)
-write the average of the 10 results to the file CALC.OUT (as the 11th. line)

AlI calculations are internal operations on the set of natural numbers (positive
integers, including ° i.e. 0, 1, 2, ... ). 'Internal' means that the result of the operation
is a member of the set of normal numbers.
The 10 results and the final result are guaranteed to be perfectly normal, l5-bit
nonnegative values, but during calculation, anything can happen! As soon as something nasty
happens, (15-bi t overflow , non-internal operation, etc.) the resul t for the current input
file is set to zero.
The 10 input files are a IL ordinary ASCII-files, containing a text, built from the
following set of words, separated by space-characters (everything in upper case)

ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,ZERO,+,-,*,/,=

These words are grouped together to form phrases like

ONE + TWO THREE / THREE

meaning: 1+23/3=

This is an example of the complicated mathematics you will encounter, only natural
numbers, addition, subtraction, multiplication and division, internal on the natural
numbers.
Calculations are simply carried out from left to right, so the result of this phrase
is 8. You will produce a result as soon as you encounter an equality-sign (so don't read the
input file further than the first equality-sign you encounter, because you may find nonsense
beyond that), or, as stated in the previous section, a zero when something goes wrong. Then,
you process the next file.
Having processed the 10 files, you also show the average over the 10 files. Again,
this calculation follows the rules of the previous second.
To allow recognition of these phrases, you will have to decode the input files first.
The encoding scheme is fairly simple. AlI you have to do is to reorder the characters in the
input file, because only the characters of the original set of words were used. You start
decoding each file by making a histogram over the entire file, i.e. you count the number of
occurrences of each character in the file. The one occurring most will be remapped onto the
space-character. The second one on the letter 'O', then 'N', 'E', 'T', 'W', 'H', 'R', F',
'UI, '1', 'V', ISI, 'X', 'G', 'ZI, '+', 1*' '/ " '=' .
Good luck ! Luck is not a factor (or should not be !)

24
Name: Bitmap RUGB91 3

Files:
program bitmap.pas
input bitmap.in
output bitmap.out

Task:

A video digitizer produces binary images of pictures containing some simple geometric
shapes. The only shapes that the image contains are triangles and rectangles (solid shapes,
not their outlines), but they can be rotated over random angles (so they need not and will
not alI have their edges parallel to the axes). For a good understanding a rectangle has
four corners of 900 Your task will be to identify aI L obj ects and return the bitmap
containing only the triangles.
Since this may not be as simple a task as it seems, we will provide you with a number
of clues:
- find a connected area (i.e.an area of set pixels that are alI liked together)
- find it's 'bounding box', i.e. the rectangle (sides parallel to the axes) which
contains the whole area
- dependent upon the maxima (reached upon the sides of the bounding box) you should be
able to determine whether the shape is a tri angle or a rectangle
- every occurring 'corner'-pixel has 5 unit pixels among it's 8 nea rest neighbours

We stress again that you are guaranteed that a Ll, shapes are ei ther triangles or
rectangles, so you need not check this ; this implies for example that every occurring line
will be straight. However, since we' re tal king about a bitmap, this line may be more of a
staircase'
The input file will be a textfile. The first line will contain the X- and Y-dimension
of the bitmap X and Y respectively «100), separated by blanks. There will be Y other lines,
each containing X characters from the set ['O', '1'], with '1' meaning that the pixel is lit.
We also guarantee that no object will touch the border of the bitmap (so the border
will contain only O' s), that no two obj ects will touch or overlap, and that the minimum
dimension of a triangle will be 3 pixels and of a rectangle pixels.
The output file should be of the same format as the input file and contain only the
triangles that were in the original image (at the same place, of course). Have fun ...

Name: Floortiles RUGB91 4

Files:
program floor.pas
input floor.in
output floor.out

Task:

A eastIe needs new floortiles. The king does not like eut floortiles, so he asks to
use as few cuts as possible. Eaeh room of the castIe is reetangular and there are zero or
more rectangular pillars in the rooms. No pillar touches another and no pillar touches the
wall. AlI dimensions are integers ranging from 1 to 32000. The number of pillars is
unlimited, as long as the pillars fit into the room. The pillars have a minimum dimension of
1 by 2 length units.
The tiles used are squares and have a size of three by three length units. They can be
eut at one or two times the unit length. In no case there may be a eut that is not adjacent

25
to a wall or a pillar. A 'cut' is defined as cutting of a piece of the floortile along a
straight line of any length. What remains of the floortile after the cut is thrown away and
is not reused later (although this part may be greater than the part that is used). The
floortiles should be laid in a regular rectangular pattern (this means that if you thi nk
away the pillars, what remains is a checkboard-pattern). It is your task to design a program
that gives the minimum number of cuts for each room.

Example o,f cu t s , ,

The input file consists of a number of blocks. The first line of each block gives the
dimensions of the room (X and Y coordinate: two integers). Ali other lines give the
coordinates of the pillars, if any (Xl, Yl, X2, Y2 coordinates: four integers, defining the
opposing corners). After each block the re is one empty line. The output file consists of a
number of lines, one for each block. On each line there is the minimum number of cuts needed
for the corresponding block. Each line, including the last one, ends with a carriage return.

(0,0)

Samples:

INPUT OUTPUT

48 120 O
10
4 30 16

12 10
2 3 4 5
2 8 4 9
6 3 8 5
6 8 8 9

26
Name: Network RUGB91 5

Files:
program network.pas
input network.in
output network.out

Task:

Since this is a programming contest, and since most of the computers seem to be linked
together in a network nowadays (only your computers are not, because you would be cheating
by stealing each other's submissions alI the time), we will devote our attention a while to
the difficulties arising on such networks, such as "Who can do what at what time on what
machine ?" . Catch my meaning ?

As an example we will use the '835'-network that you can see on the chart: it consists
of 8 terminals, linked to 3 'calculators' and further onto S printers, in exactly the same
manner as you can see on the chart. The terminals send requests to the network, asking for a
certain amount of calculation time and afterwards a certain amount of print ing time. The
requests first go into a calculator-queue before being calculate, and after calculation go
into a printer-queue before being printed . These queues both work differently, but we' II
return to this later.
The time is measured in arbitrary time-pulses. At time O alI queues are empty and alI
calculators and printers are available.
The input text file consists of an unknown number of lines. The first line describes
the network using three numbers Nl, N2, N3 (alI within [1. .10]) the number of terminals,
the number of ca1culators and the number of printers. AlI other lines (no more th an 100)
contain the data for the requests. Each request is described on a separate line by five
numbers, alI separated by blanks, and they are respectively : the time the request is sent
[1 ..100], the number of the requesting terminal [1 ..Nl], the priori ty code [1 ..5] where 5
has the highest priority, the amount of calculation time requested [1 ..20] and final ly the
amount of printing time requested [1 ..20]. Input will be such that alI occurring times will
fit into one byte (so alI requests will be completely processed before time 256).
These requests first go into the calculator-queue. At any time this queue is ordered
first by priority (higher priorities first), then by terminal number (lower terminal numbers
first) and last by request time (lower request times first). No terminal will put two
requests at the same time.

27
The calculators, when they finish processing a request, take the first request from
the calculator-queue. If two or more calculators be come available at the same time, the one
with the lowest number takes the first request. They calculate upon a request for as long as
is defined by the calculation-time of that request. Calculation can only start at the next
time-pulse after the request is put, e.g. a request entered at time 1 will start calculation
at time 2 (if the re is a calculator available, of course). This means that transferring
events to and from a queue does not consume any time.
When a calculator finishes process ing a request, it puts the request into the printer-
queue. This queue is an ordinary FIFO-queue (first in, first out) without priorities. When
two calculators finish calculating at the same time, the calculator with the lowest number
puts it's printing request first.
The printers, when they finish processing a request, take the first request from the
printer-queue. If two or more printers become available at the same time, the one with the
lowest number takes the first request. They print upon a request for as long as is defined
by the printing-time of that request.
The input file contains the terminal requests, sorted upon request time (only upon
time, no further sorting) .
The output text file should contain one line for each request, and the requests should
occur in the same order as in the input file. Each line should contain four numbers: the
calculator number that processes the request, the time at which calculation starts, the
printer number that processes the request and the time at which printing starts all
numbers should be separated by exactly one space.

Samples:

INPUT OUTPUT

8 3 5 2 2 1 12
1 1 1 10 10
1 2 1 10 10 3 2 2 12
1 3 2 12 12 1 2 5 14
1 4 1 10 10 1 14 5 26
5 10 5 1 20 2 12 3 13
6 10 5 1 20 3 12 4 13
7 10 5 1 20 2 13 1 22
10 1 1 10 10 3 13 2 23

Name: Buying a house RUGB91 6

Files:
program house.pas
input house.in
output house.out

Task:

For this next problem, we' re going to plunge into the magic of 'real estate'. Since
houseprices are rising far above the means of normal mortal souls, a solution has to be
found. The solution we will concentrate upon is that of people putting their money together
to buy a house. But more people may be interested than are really needed ...
The input file consists of a number of blocks, with each block containing the data for
one house (blocks are separated by one blank line). The first line contains the price of the
house (this price, as well as all amounts of money, are guaranteed to be non-zero positive
integers), the second line the number of people that are interested (in the range [1 ..20J )
and the rest of the block describes these people. Each of these last lines describes one

28
person: his number ("We are very discrete, Sir, everybody is anonymous !"), one or more
blanks, and the amount of money he possesses. These lines are not guaranteed to be sorted in
any way.
We define a combination as a group of one or more people who are able to buy the house
when they put their money together, but when any of the persons is taken away, they're no
longer able to buy the house (everyone in the combination is necessary to buy the house).
For example, the house costs 50, person 1 and 2 each possess 26 and person 3 possesses
10 al though they are able to buy the house, they don' t form a valid combination since
person 1 and 2 can buy the house by themselves without needing person 3.
Your task is to find the number of valid combinations for each house, and to write
these numbers on separate lines in the output file (without leading or Oailing spaces).

Samples:

INPUT OUTPUT

15 II

6 4

1 3
2 5
3 7
4 9
5 II
6 13

25
4

1 10
2 10
3 10
4 10

Name: Check! RUGB91 7

Files:
program check.pas
input check. in
output check. aut

Task:

Since alI computer programmers know how to play chess, here is a simple problem for
everyone. Your program has to determine whether white' s king is in check, in a series of
positions. The standard rules of chess apply on an 8x8 board.

The input file is formatted as follows

<white piece data> ]

<blank line> ] repeated for each position


<black piece data>
<blank line>]

For each position, the white piece data and the black piece data are sequences of
lines. These lines contain three characters each

29
- the first character is from the set {'p', 'r', 'n', 'b', 'q', 'k'} and denotes the
piece whose location is being described: pawn, rook, knight, bishop, queen and king
respectively.
- the second and third character indicate the location of this piece, coded as a
letter {'a ' 'hl} followed by a number {Ill '8'} .

Note that square el is that occupied by the white king at the start of a game.

The output file should contain one line for each position described in the input file.
Each line may contain one of two words :

check: if white's king is under attack


safe: if there is no piece threatening white's king

Ali the rules of chess apply. Note that check should be reported even if the
threatening piece is pinned. You should assume that each posi tion described in the input
file is legal. That is, the re are no errors such as two pieces occupying the same position,
or the white king being absent.

Samples:

INPUT OUTPUT

kd3 check
pe4 safe

kb8
nc5
bg6

kh3
pf3

rb3
kf8

Name: We get around ... RUGB91 8

Files:
program tour.pas
input tour. in, bus. in
output tour.out

Task:

The Poucher family are on holiday in an unfamiliar part of the country and want to
organi ze some round-trip excursions. However, the only information they have on possible
routes is a lea flet listing ali bus services to some nearby towns and their prices. The
Pouchers have drawn up a list of places to visit on a tour, but they don't know which tours,
if any, are possible by bus. Your program should combine the bus service data and their tour
list to produce a list of possible tours and the total cost of each tour. Ali the bus
services are two-way and run between exactly two towns. Since this is a sight-seeing
holiday, the Pouchers only want to use a particular bus service once.
The bus service information will be in a text file BUS.IN. Each line of this file will
contain two entirely alphabetic strings of maximum length 10 followed by a single integer,
ali separated by a single space. These represent the two towns connected by a bus service
and the price of the journey. There are at most fifty such lines.
The Poucher's short list of towns is stored in TOUR. IN. This file contains a number of
blocks, each block describing a tour. A block contains a number of place names, one per

30
line. The first line indicates the town in which the tour must start and end. The remaining
lines list the names of places which must be visi ted on the tour. These places must be
visi ted at least once in the tour, but may be visi ted in any order. Blocks are separated
from each other by one blank line.
tor each of the blocks in the TOUR.IN file, your program should report ei ther ...
Tour costs n franks.
where n is the lowest possible price for the tour, or
No route possible.
These responses should be written to TOUR.OUT, one per line

Samples:

bus.in tour.in tour.out


lovendegem evergem 1 gent Tour costs 7 franks.
nevele lovendegem 1 evergem Tour costs 20 franks.
gent evergem 3 nevele Tour costs 35 franks.
gent lovendegem 4 No route possible.
nevele gent 4 gent
gent wetteren aalst
melle gent 2
melle aalst 6 haaltert
wetteren aa1st 8 lovendegem
aalst haaltert 1
haaltert opwijk 5 gent
aalst opwijk 2 buggenhout
buggenhout opwijk 3

Name: Firetruck ACMF91 1

Files:
program a.pas
input a.inp
output a.out

Task:

The Center City fire department collaborates with the transportation department to
ma n t a n maps
í í of the city which reflects the current status of the city streets. On any
given day, several streets are closed for repairs or construction. tirefighters need to be
able to select routes from the firestations to fires that do not use closed streets.
Central City is divided into non-overlapping fire districts, each containing a single
firestation. When a fire is reported, a central dispateher alerts the firestation of the
district where the fire is located and gives a list of possible routes from the firestation
to the fire. You must wri te a program that the central dispateher can use to gene rate
routes from the district firestations to the fires.
Input and Output:
The ci ty has a separate map for each fire district. Streetcorners of each map are
identified by positive integers less than 21, with the firestation always on corner #1. The
input file contains several test cases representing different fires in different districts.
The first line of a test case consists of a single integer which is the number of the
streetcorner closest to the fire. The next several lines consist of pairs of positive
integers separated by blanks which are the adj acent streetcorners of open streets. (tor
example, if the pair 4 7 is on a line in the file, then the street between streetcorners 4
and 7 is open. There are no other streetcorners between 4 and 7 on that section of the
street.) The final line of each test case consists of a pair of O' s. tor each test case,

31
your output must identify the case by number (case #1, case #2, etc). It must list each
route on a separate line, with the streetcorners written in the order in which they appear
on the route. And it must gi ve the total number routes from firestation to the fire.
Include only routes which do not pass through any streetcorner more than once. (For
obvious reasons, the fi re department doesn' t want its trucks dri ving around in circles. )
Output from separate cases must appear on separate lines. The following sample input and
corresponding correct output represents two test cases.

Samples:

INPUT OUTPUT

6 CASE 1:
1 2 1 2 43 6
1 3 1 2 53 6
3 4 1 2 34 5 6
3 5 1 2 64
4 6 1 3 42 6
5 6 1 3 64
2 3 1 3 65
2 4 There are 7 routes from the firestation to streetcorner 6.
O O CASE 2:
4 1 3 2 5 7 8 9 6 4
2 3 1 3 4
3 4 1 5 2 3 4
5 1 1 5 7 8 9 6 4
1 6 1 6 4
7 8 1 6 9 8 7 5 2 3 4
8 9 1 8 7 5 2 3 4
2 5 1 8 9 6 4
5 7 There are 8 routes from the firestation to streetcorner 4.
3 1
1 8
4 6
6 9
O O

Name: Triangular Vertices ACMF91 2

Files:
program b.pas
input b.inp
output b.out

Task:

Consider the points on an infinite grid of equilateral triangles as shown below:

x
x x
x x x
x x x x
x x x x x

Note that if we number the points from left to right and top to bot tom, then groups
of these points form the vertices of certain geometric shapes. For example, the sets of
points {l,2,3} and {7,9,18} are the vertices of triangles, the sets {ll,13,26,24} and
(2,7,9,lB) are the vertices of parallelograms, and the sets {4,5,9,13,12,7) and
{8,lO,17,2l,32,34} are the vertices of hexagons.
Write a program which will repeatedly accept a set of points on this triangular grid,
analyze it, and determine whether the points are the vertices of one of the following
'acceptable' figures: triangle, parallelogram, or hexagon. In order for a figure to be
acceptable, it must meet the following two conditions:

32
1) Each side of the figure must coincide with an edge in the grid. and
2) All sides of the figure must be of the same length.

Input and Output


The input will consist of an unknown number of point sets. Each point set will appear
on a separate line in the file. There are at most six points in a set and the points are
limited to the range 1 ..32767.
For each point set in the input file, your program should deduce from the number of
points in the set which geometric figure the set potentially represents; e.g., six points
can only represent a hexagon, etc. The output must be a series of lines listing each point
set followed by the results of your analysis.

Samples:

INPUT OUTPUT

1 2 3 1 2 3 are the vertices of a tri angle


II 13 29 31 II 13 29 31 are not the vertices of an acceptable figure
26 II 13 24 26 II 13 24 are the vertices of a parallelogram
4 5 9 13 12 7 4 5 9 13 12 7 are the vertices of a hexagon
1 2 3 4 5 1 2 3 4 5 are not the vertices of an acceptable figure
47 47 are not the vertices of an acceptable figure
II 13 23 25 II 13 23 25 are not the vertices of an acceptable figure

Name: Concurrency ACMF91 3


Simulator

Files:
program c.pas
input c.inp
output C.out

Task:

Programs executed concurrentlyon a uniprocessor system appear to be executed at the


same time, but in reality the single CPU alternates between the programs, executing some
number of instructions from each program before switching to the next. You are to simulate
the concurrent execution of up to ten programs on such a system and determine the output
that they will produce.
The program that is currently being executed is said to be running, while all
programs awaiting execution are said to be ready. A program consists of a sequence of no
more than 25 statements, one per line, followed by an end statement . The statements
available are listed below.
Statement Type Syntax
Assignment variable = constant
Output print variable
Begin Mutual Exclusion lock
End Mutual Exclusion unlock
Stop Execution end

A variable is any single lowercase alphabetic character and a constant is an unsigned


decimal number less than 100. There are only 26 variables in the computer system, and they
are shared among the programs. Thus assignments to a variable in one program affect the
value that might be printed by a different program. All variables are ini ti al ly set to
zero.

33
Each statement requires an integral number of time uni ts to execute. The running
program is permitted to continue executing instructions for a period of time called i ts
quantum. When a program' s time quantum expires, another ready program will be selected to
run. Any instruction current ly being executed when the time quantum expires will be allowed
to complete.
Programs are queued first-in-first-out for execution in a ready queue. The initial
order of the ready queue corresponds to the original order of the programs in the input
file. This order can change, however, as a result of the execution of lock and unlock
statements.
The lock and unlock statements are used whenever a program wishes to claim mutually
exclusive access to the variables it is manipulating. These statements always occur in
pairs, bracketing one or more other statements. A lock will always precede an unIock, and
these statements will never be nested. Once a program successfully executes a lock
statement, no other program may successfully execute a lock statement until the locking
program runs and executes the corresponding unlock statement . Should a running program
attempt to execute a lock while one is already in effect, this program will be placed at
the end of the blocked queue. Programs blocked in this fashion lose any of their current
time quantum remaining. When an unlock is executed, any program at the head of the blocked
queue is moved to the head of the ready queue. The first statement this program will
execute when it runs will be the lock statement that previously failed. Note that it is up
to the programs involved to enforce the mutual exclusion protocol through correct usage of
lock and unlock statements . (A renegade program wi th no lock/unlock pair could al ter any
variables it wished, despite the proper use of lock/unlock by the other programs.)

Input and Output


The first line of the input file consists of seven integers separated by spaces.
These integers specify (in order): the number of programs which follow, the unit execution
times for each of the five statements (in the order given above), and the number of time
units comprising the time quantum. The remainder of the input consists of the programs,
which are correctly formed from statements according to the rules described above.
AlI program statements begin in the first column of a line. Blanks appearing in a
statement should be ignored. Associated wi th each program is an identification number
based upon its location in the input data (the first program has ID = 1, the second has ID
= 2, etc.).
Your output will contain of the output generated by the print statements as they
occur during the simulation. When a print statement is executed, your program should
display the program ID, a colon, a space, and the value of the selected variable. Output
from separate print statements should appear on separate lines. A sample input and correct
output are shown below.

Samples:

INPUT OUTPUT

3 1 1 1 1 1 1 1: 3
a = 4 2: 3
print a 3: 17
lock 3: 9
b = 9 1: 9
print b 1: 9
unlock 2: 8
print b 2: 8
end 3: 21
3: 21
a = 3
print a
lock
b = 8
print b
unlock
print b
end

34
b = 5
a = 17
print a
print b
lock
b = 21
print b
unlock
print b
end

Name: The Domino Effect ACMF91 4

Files:
program d.pas
input d.inp
output d.out

Task:

A standard set of Double Six dominoes contains 28 pieces (calied bones) each
displaying two numbers from O (blank) to 6 using dice-like pips. The 28 bones, which are
unique, consist of the following combinations of pips:

Bone # Pi ps Bone # Pips Bone # Pips Bone # Pips


1 O O 8 1 1 15 2 3 22 3 6
2 O 1 9 1 2 16 2 4 23 4 4
3 O 2 10 1 3 17 2 5 24 4 5
4 O 3 II 1 4 18 2 6 25 4 6
5 O 12 1 5 19 3 3 26 5 5
6 O 5 13 1 6 20 3 27 5 6
7 O 6 14 2 2 21 3 5 28 6 6

All the Double Six dominoes in a set can he laid out to display a 7 x 8 grid of pips.
Each layout corresponds at least one 'map' of the dominoes. A map consists of an identical
7 x 8 grid with the appropriate bone numbers substituted for the pip numbers appearing on
that bone. An example of a 7 x 8 grid display of pi ps and a corresponding map of bone
numbers is shown below.

7 x 8 gr id of pips map of bone numbers

6 6 2 6 5 2 4 1 28 28 14 7 17 17 11 11
1 3 2 O 1 O 3 10 10 14 7 2 2 21 23
1 3 2 4 6 6 5 8 16 25 25 13 21 23
1 O 3 2 1 1 2 8 16 15 15 13 9 9
5 1 3 6 O 4 5 5 12 12 22 22 5 5 26 26
5 5 O 2 6 O 3 27 24 24 3 3 18 1 19
6 O 5 3 4 2 O 3 27 6 6 20 20 18 1 19

Wri te a program that will analyze the pattern of pi ps in any 7 x 8 layout of a


standard set of dominoes and produce a map showing the position of ali dominoes in the set.
If more than one arrangement of dominoes yield the same pattern, your program should
generate a map of each possible layout.

Input and Output


The input file will contain several of problem sets. Each set consists of seven
lines of eight integers from O through 6, representing an observed pattern of pips. Each

35
set is corresponds to a legitimate configuration of bones (there will be at least one map
possible for each problem set). There is no intervening data separating the problem sets.
Correct output consists of a problem set label (beginning with Set #1) followed by an
echo printing of the problem set itself. This is followed by a map label for the set and
the map(s) which correspond to the problem set. (Multiple maps can be output in any order.)
After alI maps for a problem set have been printed, a summary line stating the number of
possible maps appears. At least three lines are skipped between the output from different
problem sets while at least one line separates the labels, echo printing, and maps within
the same problem set. A sample input file of two problem sets along with the correct output
are shown on the reverse of this page.

Samples:

INPUT OUTPUT

5 4 3 6 5 3 4 6 Layout #1:
O 6 O 1 2 3 1 1
3 2 6 5 O 4 2 O 5 4 3 6 5 3 4 6
5 3 6 2 3 2 O 6 O 6 O 1 2 3 1 1
4 O 4 1 O O 4 1 3 2 6 5 O 4 2 O
5 2 2 4 4 1 6 5 5 3 6 2 3 2 O 6
5 5 3 6 1 2 3 1 4 O 4 1 O O 4 1
4 2 5 2 6 3 5 4 5 2 2 4 4 1 6 5
5 O 4 3 1 4 1 1 5 5 3 6 1 2 3 1
1 2 3 O 2 2 2 2
1 4 O 1 3 5 6 5 Maps resulting from layout #1 are:
4 O 6 O 3 6 6 5
4 O 1 6 4 O 3 O 6 20 20 27 27 19 25 25
6 5 3 6 2 1 5 3 6 18 2 2 3 19 8 8
21 18 28 17 3 16 16 7
21 4 28 17 15 15 5 7
24 4 11 11 1 1 5 12
24 14 14 23 23 13 13 12
26 26 22 22 9 9 10 10

There are 1 solution (sj for layout #1.


Layout #2:

4 2 5 2 6 3 5 4
5 O 4 3 1 4 1 1
1 2 3 O 2 2 2 2
1 4 O 1 3 5 6 5
4 O 6 O 3 6 6 5
4 O 1 6 4 O 3 O
6 5 3 6 2 1 5 3

Maps resulting from layout #2 are:

16 16 24 18 18 20 12 11
6 6 24 10 10 20 12 11
8 15 15 3 3 17 14 14
8 5 5 2 19 17 28 26
23 1 13 2 19 7 28 26
23 1 13 25 25 7 4 4
27 27 22 22 9 9 21 21

16 16 24 18 18 20 12 11
6 6 24 10 10 20 12 11
8 15 15 3 3 17 14 14
8 5 5 2 19 17 28 26
23 1 13 2 19 7 28 26
23 1 13 25 25 7 21 4
27 27 22 22 9 9 21 4

There are 2 solution (s) for layout #2.

Name: Hospital Facilities ACMF91 5

Files:
program e.pas
input e.inp
output e.out

36
Task:

County General Hospital is trying to chart its course through the troubled waters of
the economy and shifting population demographics. To support the planning requirements of
the hospital, you have been asked to develop a simulation program that will allow the
hospital to evaluate alternative configurations of operating rooms, recovery rooms and
operations guidelines. Your program will monitor the usage of operating rooms and recovery
room beds during the course of one day.
County General Hospital has several opera ting rooms and recovery room beds. Each
surgery patient is assigned to an available operating room and following surgery the patient
is assigned to one of the recovery room beds. The amount of time necessary to transport a
patient from an operating room to a recovery room is fixed and independent of the patient.
Similarly, both the amount of time to prepare an operating room for the next patient and the
amount of time to prepare a recovery room bed for a new patient are fixed.
All patients are officially scheduled for surgery at the same time, but the order in
which they actually go into the operating rooms depends on the order of the patient roster.
A patient entering surgery goes into the lowest numbered operating room available. For
example, if rooms 2 and 4 be come available simultaneously, the next patient on the roster
not yet in surgery goes into room 2 and the next after that goes into room at the same
time. After surgery, a patient is taken to the available recovery room bed with the lowest
number. If two patients emerge from surgery at the same time, the patient with the lower
number will be the first assigned to a recovery room bed. (If in addition the two patients
entered surgery at the same time, the one first on the roster is first assigned a bed.)

Input and Output


The input file contains data for a single simulation run. Ali numeric data in the
input file are integers, and successive integers on the same line are separated by blanks.
The first line of the file is the set of hospital configuration parameters to be used for
this run. The parameters are, in order:

Number of operating rooms (maximum of 10)


Number of recovery room beds (maximum of 30)
Starting hour for 1st surgery of day (based on a 24-hour clock)
Minutes to transport patient from operating room to recovery room
Minutes to prepare operating room for next patient
Minutes to prepare recovery room bed for next patient
Number of surgery patients for the day (maximum of 100)

This ini ti al configuration data will be followed by pairs of lines of patient data as
follows:
Line 1: Last name of patient (maximum of 8 characters)
Line 2: Minutes required for surgery. Minutes required in the recovery room

Patient records in the input file are ordered according to the patient roster, which
determines the order in which patients are scheduled for surgery. The number of recovery
room beds specified in any configuration will be sufficient to handie patients arriving from
surgery (No queuing of patients for recovery room beds will be required). Computed times
will not extend past 24:00.
Correct output shows which operating room and which recovery room bed is used by each
patient, and the time period that the patient us es the room and bed along with a summary of
the utilization of hospital facilities for that day. The output file consists of a set of
two tables describing the res ul ts of the simulation run. The first table is in columnar
form wi th appropriate column labels to show the number of each patient (in the order the
patient roster), the patient's last name, the operating room number, the time surgery beings
and ends, the recovery bed number and the time the patient enters and leaves the recovery
room bed.

The second table will also be in columnar form with appropriate column labels
summarizing the utilization of operating rooms and recovery room beds. This summary

37
indicates the facility type (room or bed), the facility number, the number of minutes used
and percentage of available time utilized. Available time is defined as the time in minutes
from the starting time for 1st surgery of day to the ending time of the last patient in a
recovery room bed. A sample input file and corresponding correct output are shown below.

Samples:

INPUT OUTPUT

5 12 07 5 15 10 16 # Name Room# Begin End Bed# Begin End


Jones ------------------------------------------------------
28 140 1 Jones 1 7:00 7:28 3 7:33 9:53
Smith 2 Smith 2 7:00 9:00 1 9:05 12:25
120 200 3 Thompson 3 7:00 7:23 2 7:28 8: 43
Thompson 4 Albright 4 7:00 7:19 1 7:24 8: 46
23 75 5 Poucher 5 7:00 9:13 5 9:18 12:47
Albright 6 Comer 4 7:34 8:48 4 8:53 10:34
19 82 7 Perry 3 7:38 9:11 2 9:16 12:24
Poucher 8 Page 1 7: 43 9:34 6 9:39 13:22
133 209 9 Roggio 4 9:03 10:12 9 10:17 12:19
Comer 10 Brigham 2 9:15 9:57 8 10:02 ll: 21
74 101 II Nute 3 9:26 9: 48 7 9:53 ll: 04
Perry 12 Young 5 9:28 10:06 3 10:11 12:31
93 188 13 Bush 1 9: 49 10:15 10 10:20 12:21
Page 14 Cates 3 10:03 12:03 8 12:08 16:16
III 223 15 Johnson 2 10:12 11:38 4 ll: 43 14: 44
Roggio 16 White 5 10:21 11:53 7 ll: 58 14:18
69 122
Brigham Faci1ity Uti1ization
42 79 Type # Minutes % Used
Nute -------------------------
22 71 Room 1 165 29.68
Young Room 2 248 44.60
38 140 Room 3 258 46.40
Bush Room 4 162 29.14
26 121 Room 5 263 47.30
Cates Bed 1 282 50.72
120 248 Bed 2 263 47.30
Johnson Bed 3 280 50.36
86 181 Bed 4 282 50.72
White Bed 5 209 37.59
92 140 Bed 6 223 40.11
Bed 7 211 37.95
Bed 8 327 58.81
Bed 9 122 21.94
Bed 10 121 21. 76
Bed II O 0.00
Bed 12 O 0.00

Name: Message Decoding ACMF91 6

Files:
program f.pas
input f.inp
output f.out

Task:

Some message encoding schemes require that an encoded message be sent in two parts.
The first part, ca11ed the header, contains the characters of the message. The second part
contains a pattern that represents the message. You must write a program that can decode
messages under such a scheme.
The heart of the encoding scheme for your program is a sequence of "key" strings of
O's and l's as follows:
0,00,01,10,000,001,010,011,100,101,110,0000,0001, ... ,1011,1110,00000,

38
The first key in the sequence is of length 1, the next~ are of length 2, the next 7
of length 3, the next 15 of length 4, etc. If two adjacent ~éys have the same length, the
second can be obtained from the first by adding 1 (base 2). Notice that the re are no keys
in the sequence that consist only of l's.
The keys are mapped to the characters in the header in o rd.er . That is, the first key
( O) is ma pp ed to the first character in the header, the second key (00) to the second
character in the header, the kth key is mapped to the kth character in the header. For
example, suppose the header is:

AB#TANCnrtXc

Then O is mapped to A, 00 to B, Ol to #, 10 to T, 000 to A, 110 to X, and OQ.OO


to c.
The encoded message contains only O' s and l' s and possibly carriage returns, which
are to be ignored. The message is divided into segments. The first 3 digits of a segment
give the binary representation of the length of the keys in the segment. For example, if
the first 3 digits are 010, then the remainder of the segment consists of keys of length 2
(00, Ol, or 10) The end of the segment is a string of l's which is the same length as the
length of the keys in the segment. So a segment of keys of length 2 is terminated by ll.
The entire encoded message is terminated by 000 (which would signify a segment in which the
keys have length O). The message is decoded by translating the keys in the segments one-
at-a-time into the header characters to which they have be en mapped.

Input and Output


The input file contains several data sets. Each data set consists of a header, which
is on a single line by itself, and a message, which may extend over several lines. The
length of the header is limited only by the fact that key strings have a maximum length of
7 (lll in binary). If the re are multiple copies of a character in a header, then several
keys will map to that character. The encoded message contains only O's and l's, and it is
a legitimate encoding according to the described scheme. That is, the message segments
begin with the 3-digit length sequence and end with the appropriate sequence of l's. The
keys in any given segment are alI of the same length, and they alI correspond to characters
in the header. The message is terminated by 000. Carriage returns may appear anywhere
within the message part. They are not to be considered as part of the message.
For each data set, your program must write its decoded message on a separate line.
There should not be blank lines between messages. Sample input and corresponding correct
output are shown below.

Samples:

INPUT OUTPUT

TNM AEIOU TAN ME


0010101100011 ##*\$
1010001001110110011
11000
$#**\
0100000101101100011100001000

Name: Code Generation ACMF91 7

Files:
program g.pas
input g.inp
output g.out

39
Task:

Your employer needs a backend for a translator for a very SIC machine (Simplified
Instructional Computer, apologies to Leland Beck). Input to the translator will be
arithmetic expressions in post fix form and the output will be assembly language code.
The target machine has a single register and the following instructions, where the
operand is either an identifier or a storage location.

L load the operand into the register


A add the operand to the contents of the register
S subtract the operand from the contents of the register
M multiply the contents of the register by the operand
O divide the contents of the register by the operand
N negate the contents of the register
ST store the contents of the register in the operand location

An ari thmetic operation replaces the contents of the register wi th the expression
result. Temporary storage locations are allocated by the assembler for an operand of the
form '$n' where n is a single digit.

Input and Output


The input file consists of several legitimate postfix expressions, each on a separate
line. Expression operands are single letters and operators are the normal arithmetic
operators (+, =, r , j) and unary negation (@). Output must be assembly language code that
meets the following requirements:

1. One instruction per line with the instruction mnemonic separated from the
operand (if any) by one blank.
2. One blank line must separate the assembly code for successive expressions.
3. The original order of the operands must be preserved in the assembly code.
4. Assembly code must be generated for each operator as soon as it is encountered.
5. As few temporaries as possible should be used (given the above restrictions).
6. For each operator in the expression, the minimum number of instructions must be
generated (given the above restrictions).
A sample input file and corresponding correct output are on the reverse of this
paper.

Samples:

INPUT OUTPUT

AB+CD+EF++GH+++ LA
AB+CD+ A B
ST $1
L C
A D
ST $2
L E
A F
A $2
ST $2
L G
A HA $2
A $1

L A
A B
ST $1
L C
A D
N
A $1

40
Name: Bit Twiddler USSC92 1

Files:
program bit.pas
input bit.in
output bit. aut

Task:

A Gray code is a series of bit patterns in which successive values in the code differ
in only one bit position
For example, the following 3-bit Gray code could be used to encode the digits from O
through 7:

GC Decimal This example is only one of a number of possible Gray codes for
000 O 3-bi t values Gray codes are commonly used when analog data must be
100 1 sampled and then converted to digital form. Since only one bit changes
101 2 between the successive values in the code, ambiguity is reduced when
001 3 the conversion must be carried out on ana log data which is at the
Oll thresholds between two potential digital values.
010 5
llO 6
III 7

This example is only one of a number of possible Gray codes for 3-bit values Gray
codes are commonly used when analog data must be sampled and then converted to digital form.
Since only one bit changes between the successive values in the code, ambiguity is reduced
when the conversion must be carried out on analog data which is at the thresholds between
two potential digital values.
A special property of certain Gray codes is circularity, i.e. the bit pattern used to
encode the first and 1 values also differ in exactly one bit position. Since this is not the
case in the above Gray code, it is not circular 3-bit circular Gray code is shown below.

Gray Code Decimal Equivalent


000 O
001 1
011 2

010 3
llO 4
III 5
101 6
100 7

Notice that in this circular Gray code, the code begins with a code for zero (alI O-
bi ts) and the remindingD the code was generated according to the following rule: the
frequency with which a bit position flips its value half of the frequency of the bit
position to its immediate right - thus the rightmost bit varies the most frequent and the
leftmost bit varies the least of ten . Your task is to develop a program which can answer
inquiries aboutD circular Gray codes of size 1 to 15 bits (inclusive) generated in this
manner. These inquiries will ask you to generate the bit patterns used to encode a subrange
of the integer values represented by the circular Gray code of a cer1 size. Note that only
the non-negative integer values starting from zero will be encoded.

INPUT

41
The input to this program will consist of a series of inquiries in a text file. Each
inquiry wi)l occur on a line by and will consist of three integers (separated by at least
one space) in the following format:

code length range decimal #1 range decimal #2

For example, the inquiry: 2 O 3 means to display the bit patterns used to encode the
integers from O to 3 the 2-bit circular Gray code; the inquiry: 5 24 19 means to display the
bit patterns used to encode the integers from 19 to 24 using the 5-bit circular Gray code.
There are an unknown number of input inquiries in the file.
The output for this program will consist of a two-column table (with headers) for a Ll,
valid inquiries an messages for each invalid inquiry. N06ce that for valid inquiries, the
code table is always printed in a order, regardless of the original order of the range
integers. The output resulting from each inquiry m separated by three blank lines.

Samples:

INPUT OUTPUT

2 O 3 Decimal Value 2-Bit Code


5 24 19
37 8 13 O 00
8 2 6 1 Ol
4 36 41 2 II
3 10

Decimal Value 5-Bit Code

19 11010
20 11110
21 11111
22 11101
23 11100
24 10100

LENGTH ERROR: 37 Bits Requested

Decimal Va1ue 8-Bit Code

2 00000011
3 00000010
4 00000110
5 00000111
6 00000101

RANGE ERROR: 4 Bits Cannot Encode 36 to 41

Name: Tempus Fugit USSC92 - 2

Files:
program tempus.pas
input tempus.in
output tempus.out

Task:

The owner of a successful small business is so busy that she requires all of her
appointments to be scheduled two weeks in advance. She has contacted you to write a program
that will help her automate this process. H week lasts from 9:00 a.m. to 5:00 p.m., Monday
through Friday. She leaves for 1unch at 12:30 p.m. and return 1:3Q p.m. each day.

42
During the week, she collects appointment requests for two weeks in advance in the
order that they made. Your program will process the requests in the same order, e.g. giving
priority to those requests were made the earliest. After running your program, she will
confirm the scheduled appointments and reschedule those appointments that the program could
not arrange for her.
She asks that your program schedule her appointments in ten-minute blocks that begin
on the hour ten-, twenty-, thirty-, forty-, and fifty-minutes past the hour. Any requests
that do not begin and/or end at th minute points in time must be scheduled between the ten-
minute points which encompass them. For example appointment request for 10:15 a.m. to 10:30
a.m. would be scheduled from 10:10 a.m. to 10:30 a.m.
She also wants your program to insert a ten-minute break after each scheduled
appointment so that appointments occur in immediate succession. The ten-minute break will
occupy the next ten-minute block on schedule. Ten-minute breaks are not to be added for
appointments which can be scheduled to end at 12:30 p. 5:00 p.m. No appointment is permitted
to extend into the lunch period, or to be scheduled to begin during the period. She would
like no more than four hours of appointments scheduled on any one day. When computing four-
hour limit, use the adjusted length of the appointment (do not use the length of the
original request and include the ten-minute breaks which follow the adj usted appointment
times) . Thus the appointment request 10:15 a.m. to 10:30 a.m. contributes 20 minutes to the
four-hour time limit for that day.
Finally, the owner telIs you that if an appointment cannot be scheduled as requested,
your program should attempt to reschedule the appointment at the same time on each
successive day of the week, scheduling it on first day that it fits: if an appointment
cannot be scheduled at. 10:00 a.m. on Wednesday your program would try to schedule it on
Thursday at 10:00 a.m., and then Friday at 10:00 a.m. if it cannot be scheduled on Thursday
(do not attempt to reschedule the appointment earlier in the week or at different times of
the day). If your program cannot schedule the appointment in this ma nrie r , the name of the
person requesting the appointment should added to the list of appointments that could not be
scheduled.

INPUT
The input file will consist of at most 25 appointment requests on a separate line in
the following form

name day start time duration

where the name field occupies the first ten character positions of the request, the
day field occupies the next three character posi tions, and the remaining two fields each
consist of a pair of integers. The name field will contain ten alphanumeric characters and
the day field will contain the three characters MON, TUE, WED, THU, or FRI. Following the
day will be two times: the starting time of an appointment request, and its duration. Both
times consist of two integers, hours followed by minutes. For example, the appointment
request JOHNSTONE TUE 09 15 1 30 means that Johnstone requests an appointment for the
Tuesday of that week starting at 9:15 a.m. for one hour and thirty minutes. Since the
schedule is in ten-minute blocks, your program would attempt to schedule this appointment
for Tuesday from 9:10 a.m. to 10:50 a.m. (adding 1 hour and 40 minutes to the total
appointment time on Tuesday. Your program may assume that a I.L fields in an appointment
request will contain legitimate data and that times will be express ed in terms of the
maximal number ofhours (9:15 a.m. will always be 09 15 rather than 08 75 and ninety minutes
will always be 1 30 rather than O 90).
Your output will consist ofa schedule for the week followed by a summary listing the
names of those people whose appointments could not be scheduled during this time. Days with
no scheduled appointments should be note.

43
Samples:

INPUT OUTPUT

Johnstone TUE 09 15 1 30 APPOINTMENT SCHEDULE FOR THE WEEK


Peterson MON 09 00 O 30
McKeever FRI 09 30 1 00 MONDAY
Garzarelli THU 10 45 O 20 Peterson 9:00 to 9:30
Tucker MON 10 00 2 30 Tucker 10:00 to 12:30
Davis MON 02 30 1 00 Davis 2:30 to 3:30
Corrigan MON 02 00 O 15
Trump WED Ol 00 3 00 TUESDAY
Logan THU 09 45 1 05 Johnstone 9:10 to 10:50
Schulman THU II 10 O 30 Corrigan 2:00 to 2:20 O
WEDNESDAY
No Appointments Scheduled

THURSDAY
Garzarelli 10:40 to 11:10

FRIDAY
McKeever 9:30 to 10:30
Schulman ll:10 to ll:4O

APPOINTMENTS COULD NOT HE SCHEDULED FOR

'( Trump
Logan

Name: Stellar Speller USSC92 - 3

Files:
program stel.pas
input stel.in
output stel.out

Task:

The object of a Stellar Speller puzzle


is to locate words that have been hidden in
the puzzle diagram. An example of a Stellar
Speller puzzle diagram is given to the
below
Words are forrned by starting at any
letters and following one of the connecting
lines to another letter, continuing until a
word has been spelled completely.
Letters in the diagram can be reused
within the same word, but you may not
remain the on letter and use it twice in
succession nor may you jump over letters in
order to form a words. For example, the
words GRID, BURDEN, LUGGAGE legitimately
appear in the puzzle shown, but the words
GRIND, BUGLE, RIDDEN do not.

A Stellar Speller puzzle always contains precisely thirteen letters interconnected in


the exact manner as shown above. Wri te a program which can determine whether or not each
word of an input list is hidden in agiven Stellar Speller puzzle diagram.

INPUT

44
The input data for this program consists of a series of puzzle sets. One puzzle set
contains three parts: the puzzle characters, the number of words to be verified, and a list
of those words.
The puzzle characters will appear on the first line of the puzzle set starting in the
first character position They will be given in top-to-bottom, left-to-right order - thus the
sample puzzle would appear in the input data as the single line ASBSNGUDLISGR. Only
uppercase alphabetic characters will appear in a puzzle.
The number of words in the verification list will be given as a positive integer on
the second line of the puzzle set. The verification list will contain at least one word and
no more than twenty words.
The verification list will begin on the third line of the puzzle set. Sach word in the
verification list willoccur on a line by itself beginning in the first character position.
Words will consist of uppercase alphabetic characters only and will be from one to fifteen
characters in length.
You may assume that ali input data adheres to the standards outlined above - no error
checking of the input data is necessary for this problem. There are an unknown number of
puzzle sets in the input file.

OUTPUT
The output of this program will consist of a puzzle number heading (which includes
column headings followed by the list of words separated into a two-column listing of words
that appear and do not appear in the puzzle. A blank line must separate the output from
consecutive puzzle sets.

Samples:

INPUT OUTPUT

AEBENGUDLIEGR PUZZLE #1
10 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLE
GRID
BURDEN GRID RIDDEN
RIDDEN BURDEN BEAN
REUBEN REUBEN BUGLE
BEAN LUGGAGE GRIND
BUGLE DIRE AGELESS
GRIND
AGELESS
LUGGAGE
DIRE
ABCDEFGHIJKLM PUZZLE #2
1 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLE
FILM
FILM

IOCBDTARGEFMS PUZZLE #3
9 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLE
TARGET
START AS TARGET
AS DREAMS START
RIOT ERASER RIOT
DREAMS DREARY FACES
DREARY DOORS
FACES
ERASER
DOCRS

Name: Railroad Safety ODUN92 1

Files:

program railroad.pas
input railroad.inp
output railroad.out

45
Task:

Consider the following street/railroad crossing. There are two parallel tracks crossing
sing Colonial Avenue. Each track has sensors placed 500 feet from either side of the street.
Sensors send a signal to a controller when they are first pressed and when they are
released. You are asked to program the controller for a safety traffic gate system at the
railroad crossin
tor specificity, suppose we use the following naming conventions. The tracks are
numbered TI and T2. Sensors for each track are SO and SI. Sensors send information to thee
controller when they are first pressed and when they are released. Trains can travel either
direction on either track; however, may assume that trains will not reverse direction in the
middie of the crossing and that there are no train crashes.
Your program should be set to accept standard input that indicates a change in one of
the sensors (track_no, sensor_no, [P I R]) Where track no is TI, or T2, sensor no is SO or
SI, P stands for "pressed", and R for "released" A single Q on a line terminates the program.
Upon receiving such input your program should output one of the following four
possibili ties: crossing gates close, crossing gates remain closed, crossing gates open,
crossing gates remain open.
You may assume that you receive no illegal input; for example, if there are currently
no trains and a Ll switches are released, then you could not receive the signal - T2 SO
released.

Samples:

INPUT OUTPUT

TI SO Pressed crossing gates close


TI SI Pressed crossing gates remain closed
TI SI Pressed crossing gates remain closed
Tl SO Released crossing gates open
Q

Name: Interval Arithmetic ODUN92 2


Files:

program inter.pas
input inter.inp
output inter.out

Task:

Compilers for Pascal and many other languages are supposed to gene rate code that
checks array subscripting expressions for possible out-of-range violations.
tor example, the code
VAR
J: integer;
A: ARRAY [1 ..30] Ot INTEGER;
BEGIN
READ(J) ;
A[J] :=0;

should behave as if the final statement actually were

IF J > = 1 and J < = 30 THEN


A[J] :=0

46
ELSE
SIGNAL_AN_ERROR;

Clearly, this extra code increases both the space and time required by the running
program. Smart compilers will therefore only generate this checking code when actually
necessary.
For example, in the program

VAR
J: 1. .10;
A: ARRAY [1 ..30] OF INTEGER;
BEGIN
READ (J);
A[2*J+5] :=0;

no special checks are necessary for the array subscript, because the READ statement
will check to be sure that the number just read is actually in the range 1. .10 before
assigning it to J. Then, because J is in the range 1 ..10, 2*J+5 must be in the range 7 ..25,
guaranteed to represent a legal subscript value for the array A.
This kind of reasoning is called "Interval Arithmetic". Write a program that performs
single interval arithmetic operations on integers under the operations of addition,
subtraction, multiplication, and division.
Input
The input will consists of three lines. The first line will contain pair of integer
values denoting the "X range" The second line will contain another pair of integer values
denoting the "Y range". The third line will contain one of the characters '+', '*', or
'/ ' .
Output
Your output should be two integer va1ues denoting the minimum and maximum values that
could be obtained by evaluating "x op y" where x is any integer drawn from the X range, y is
any number drawn from the Y range, and op operator in the third line.
NOTES
Ignore the possibility of calculations overflowing the largest/smallest possible
integer. Even if zero is contained within the Y range, assume zero is never actually used
for a y value in "x / y" problems.

Samples:

INPUT OUTPUT
1 10 -9 II
-10 1 -8 8
+
-1 8
-10 2
/

Name: The Cat' s Stroll ODUN92 3


Files:

program cat.pas
input cat.inp
output cat.out

47
Task:

8very morning, a small cat roams the city for some time, eventual returning right back
where he started Being arather superstitious creature, he never cross es his own path
during one of these walks. (The cat is, of course, black, and everyone knows that it's bad
luck to have black cat cross your path.)
In this part of the ci ty the ci ty blocks a re laid out as perfect squares. Wri te a
program to determine the area enclosed by the cat's walk.

INPUT
8ach line of input describes one straight-line segment of the cat's 8ach line of input
will contain a letter indicating a direction (N, S, 8, or W) and an integer distance
(measured in "blocks"). The input terminated by a blank line.

OUTPUT
The output should be a single integer indicating area enclosed by the cat' s walk
(measured in blocks squared).

Samples:

INPUT OUTPUT

N 3 10
8 1
N 1
W 2

W 1
5 3
8 1
S 1

W 1

S 1
8 2
N 1

Name: Network ODUN92 4


Construction

Files:

program network.pas
input network.inp
output network.out

Task:

n different databases are distributed over n locations. These locations are to be


networked so that every database can be accessed from any location. Given a set of pairs of
locations to be connected by a direct link and the construction cost for each link
(connecting a pair of locations), design network with the minimum construction cost.

Input:

48
First line gives the number of locations, n, which are to be numbered from 1 to n.
Second line gives the required direct connections as pairs of integers from 1 to n. The
remaining lines give an n by n table of connection costs between pairs of nodes.

Output:
A network with the minimum construction cost in the form of a set pairs of locations,
and its construction cost.

Samples:

INPUT OUTPUT
4 connections: 1-2 1-3 3-4 cost: 23
1 2
O 8 10 30
8 O 20 10
10 20 O 5
30 10 5 O

Name: Code ODUN92 5

Files:

program code.pas
input code.inp
output code.out

Task:

A set of words is to be transmitted as messages. To save transmission time we want to


represent each word by one of the letters in the word such words will be uniquely
represented. Devise an algorithm to test if such representation is possible for a given set
of words.

Input:
A set of words, one per line, terminated by an empty line

Output:
Yes or No, and with a representation if Yes.

Samples:

INPUT OUTPUT

IN NO
INN
ON Yes
NO S SAW
SAW A WAS
WAS D TODAY
TODAY M HANDSOME
HANDSOME GUY U GUY

49
Name: The Thief of TUBP92 - 1
Baghdad

Files:
program a.pas
input a.dat
output a.rest

Task:

The Baghdad Office Building is on fire. On each floor of this high-rise building (at
most 150 floors, numbered from 1 to 150) there is a sack of gold coins. Your task is to
determine the maximum number of coins that can be safely retrieved subject to the following
conditions:
l. You must use the elevator which moves at a speed of 10 floors per minute.
2. You are in the elevator on the first floor when the fire starts.
3. The elevator cannot safely pass through a floor which is on fire.
4. It takes you 10 seconds to retrieve the sack of coins on any floor.
5. The fire spreads down at a rate of 1 floor per minute.
You are not able to safely retrieve the coins if the fire will arrive at that floor
while you are there. Once you have finished retrieving the coins on any floor, you are
assumed to have left that floor.
The input consists of series of numbers. Each series starts with an integer specifying
the floor on which the fire starts, followed by pairs of integers specifying a floor number
and the number of coins on that floor. Floor numbers can occur in any order. In case a floor
number occurs more than once the last occur rence should be accepted . Other floors are
assumed to have no coins. A single O floor number indicates the end of one series. The input
ends when the file ends.
The output should contain a series of numbers equal to the coins retrieved.

Samples:

INPUT OUTPUT

17 71

3 15 6 8 4 3 5 8 la 7 9 9 15 7 136

13 9 17 8 16 II 18 9 21 8 14 5 o
o 5

32

3 15 6 8 4 3 5 8 la 7 9 9 15 7

13 9 17 8 16 II 18 9 21 8 14 5

22 7 30 4 26 5 27 7 28 6 31 5
29 4 O
O O
3
1 2 2 3 3 4 O

50
Name: Urban Elevations TUBP92 - 2

Files:
program b.pas
input b.dat
output b.res

See ACMF92-7

Name: Triangular Vertices TUBP92 - 3

Files:
program c.pas
input c.dat
output c.res

See ACMF91-2

Name: The Snake in the TUBP92 - 4


Grass

Files:
program d.pas
input d.dat
output d.res

Task:

Peter's Garden is a rectangular piece of ground with integer dimensions M x N square


units (M and N at least 2 and at most 30). Each square is identified by a coordinate pair
(x,y), O <= x < M and O <= Y < N. His Garden is a big rne s s , it is infested with huge lxl
holes and rocks. The worst thing, however, is the presence of a monotonic sna ke, yukkee.
(This is not the name of the snake, but an expression of disgust. 1 just don't like snakes.
But, since you insist, let' s call her Yukkee anyway.) When Yukkee slithers around she is
always within the boundaries of a 2x3 (or 3x2) L-shaped area of 4 square units. This is
called her (momentaryl configuration. There are eight configuration classes, one of them is:

51
The question is whether Yukkee can move from one corner of the Garden to the other.
The holes and rocks are inaccessible. Moving, in this case, means changing the coordinate
pair of one square of Yukkee's configuration under invariance of the L-shape. You may choose
any ini ti al configuration for Yukkee such that it covers square (0, O). Yukkee has reached
the other corner when one of her coordinate pairs is (M-l,N-l).
Oh, by the way, you know, of course, that the species of monotonic snakes has a
limited ability to manoeuvre. Let xmin be the minimum of the x-coordinates of the squares in
the current configuration, and similarly ymin the minimum of the y-coordinates. (N.B.
(xmin,ymin) need not be in the configuration.) The new coordinates x' and y' of the changed
square (Le. after the move) must still satisfy x' >= xmin and y' >= ymin. For instance,
from the configuration {(10,10), (10,11), (10,12), (1l,10)} Yukkee can move to
{(10,10),(10,11),(11,10),(12,10)} but not to {(10,10),(10,11),(10,12),(9,12)} (even though
the latter configuration is correctly shaped) .
Write a program to determine (the existence of) a path for Yukkee in a number of
Gardens.
The input file is a textfile that presents a sequence of Gardens . Bach Garden is
described as follows. The first line gives M and N. The next line gives k, the number of
inaccessible squares in the Garden. The following k lines each contain the coordinate pair
of one inaccessible square. Gardens are not separated in the input file.
The output file is also a textfile. For each input Garden you put Yukkee in some
ini tial configuration and move her to the other corner . If this cannot be done, then your
program outputs a line with the message 'NO'. Otherwise, it outputs a line with the message
'YBS', followed by the description of a path. A path is specified by a sequence of
coordinate pairs (each pair on a line by itself. coordinates separated by one blank). The
first four lines must represent the initial configuration, each following line gives the new
coordinates of the square that changed. The last line should encode (M-l,N-l). It can be
assumed that there is at most one solution for each Garden. Solutions are not separated in
the output file.
Here follows an example of input with acceptable output:

Samples:

INPUT OUTPUT

4 4 YBS
6
2
° ° 1
O

1 O
°
1 1
1 3 2 1
2 2 2
3
°
1 2 3
3 2 3 3
4 5 NO
3
2 2

°
3
O
2

52
Name: Wetlands of Florida TUBP92 - 5

Files:
program e.pas
input e.dat
output e.res

Task:

A construction company owns a large piece of real estate within the state of tlorida.
Recently, the company decided to develop this property. Upon inspection of the property,
however, it was revealed that the land, at various locations, contained bodies of water.
This carne as a shock to the owners of the company, for they were from out of state and not
familiar with wetlands of tlorida. The situation was very grave and the owners not knowing
that such bodies of water can be converted to beautiful lakes that will increase the value
of the land around them, were about to abandon the construction project. tortunately, this
fact was brought to the owners' attention by a smart graduate student, who worked for the
company and consequently the construction project started.
The engineers divided the construction site by a grid into uni form square cells such
that each square entirely contained either water or land. (How they did it, of course, is
anybody's guess.) Now, the question that the engineers are to answer is the following:
"Given the row and column number of a grid cell that contains water, what is the area of the
lake containing that cell." An area is measured by the number of grid cells it contains. You
are to write a program to answer this question!
The input consists of O < n <- 99 lines, each containing O < m <- 99 character long
sequence of "L"s and "W"s, followed by k > O lines, each containing a pair of integers i and
j. The first n lines will represent the n by m grid covering the land where a "W"I"L" at the
cth character of the rth line indicates waterland within the cell at row r and column c of
the grid. The pairs of integers on the last k lines, each represent the row and column
numbers of some grid cell that contains water.
The output for each pair of integers, i and j, on the last k lines of input, consists
of an integer, on separate line, indicating the area of the lake containing the grid cell,
at row i and column j of the grid.
Samples:

INPUT OUTPUT

LLLLLLLLL 12
LLWWLLWLL 3
LWWLLLLLL
LWWWLWWLL
LLLWWWLLL
LLLLLLLLL
LLLWWLLWL
LLLLWLLLL
LLLLLLLLL
3 2
7 5

Name: Arbitrage TUBP92 - 6

Files:
program f.pas
input f.dat
output f.res

53
Task:

The use of computers in the finance industry has been marked with controversy lately
as programmed trading - designed to take advantage of extremely small fluctuations in
prices - has been outlawed at many Wall Street firms. The ethics of computer programming is
a fledgling field with many thorny issues.
Arbitrage is the trading of one currency for another with the hopes of taking
advantage of small differences in order to achieve a profit. For example, if $1.00 in U.S
cur rency buys 0.7 British pounds cur reney, ?1 in British currency buys 9.5 Freneh francs,
and 1 Freneh franc buys 0.16 in U.S do11ars, then an arbitrage trader can start with $1.00
and earn 1 x 0.7 x 9.5 x 0.16 = 1.064 dollars thus earning a profit of 6.4 percent.
You will write a program that determines whether a sequence of currency exchanges can
yield a profit as described above.
To result in successful arbitrage, a sequence of exchanges must begin and end with the
same curreney, but any starting currency may be considered.
The input file consists of one or more conversion tables. You must solve the arbitrage
problem for each of the tables in the input file.
Each table is preceded by an integer n on a line by itself giving the dimensions of
the table. The maximum dimension is 20; the minimum dimension is 2.
The table then follows in row major order but with the diagonal elements of the table
missing (these are assumed to have value 1.0). Thus the first row of the tab1e represents
the conversion rates between country 1 and n-1 other countries, i.e., the amount of currency
of country i (2 <= i <= n) that can be purchased with one unit of the currency of country 1.
Thus each table consists of n+1 lines in the input file: the first line containing n
and n lines representing the conversion table.
For each table in the input file you must determine whether a sequence of exchanges
exists that results in a profit of more than 1 percent (1.01).
Ifa sequence exists you must print the sequence of exchanges that resul ts in a
profit. If the re is more than one sequence that resu1ts in a profit of more than 1 percent
you must print a sequence of minimal length, i.e., one of the sequences that uses the fewest
exchanges of currencies to yield a profit. If there is more than one sequence of the same
length, you must print them alI. Circular rotations of sequences do not count as different
sequences, thus 1 2 3 1 is the same as 3 1 2 3.
Because IRS (U. S. Internal Revenue Service) notices lengthy trans action sequences,
ali profiting sequences must consist of n or fewer transactions where n is the dimension of
the table giving conversion rates. The sequence 1 2 1 represents two conversions.
If a profiting sequence exists you must print the sequence of exchanges that res ul ts
in a profit. The sequence is printed as a sequence of integers with the integer i
representing the line number i of the conversion table (country il. The first integer in the
sequence is the country from which the profiting sequence starts. This integer also ends the
sequence.
If no profiting sequence of n or fewer transactions exists, then the line

no sequence exists

should be printed.
The results for each tables must be separated by a blank line.

Samples:

INPUT OUTPUT

3 1 2 1
1.2 0.89
0.88 5.1
Ll 0.15

54
4 2 3 2
3.1 0.0023 0.35 1 3 1

0.21 0.00353 8.13 1 2 1

200 180.559 10.339 1 2 3 1

2.11 0.089 0.06111


2 no sequence exists
2.0
0.45

Name: Kombináció Kl TE92 - 1

Files:
program a.pas
input a.inp
output a.out
r:
\
Task:

A feladat olyan program írása, mely lexikografikus sorrendben felsorolja N kü l öribö zö

elem (természetes számok 1-tol N-ig) összes k-ad rendű ismétlés nélküli kombinációját.

Az INPUT file:
Tartalmazhat több eset leírást is. Az input file minden sora egy eset leírást
tartalmaz. Egy esetet úgy adunk meg, hogy egy sorban megadjuk az N és a k számot. (Az N és
k kisebb mint 100.)

Az OUTPUT file:
Soronként közli az egyes kombinációkat, a kü Lönbö zö esetek kö zö t t egy üres sort
tartalmaz.

Samples:

INPUT OUTPUT

3 2 12
4 3 13
23

123
124
134
234

Name: Prím Kl TE92 - 2

Files:
program b.pas
input b.inp
output b.out

55
Task:

A feladat olyan program írása, amely a természetes számok halmazán egy zárt
intervallumban megkeresi az összes olyan prímszámot, amely rendelkezik a következo
tulajdonságokkal:
- Ha a számnak elhagyjuk a legkisebb helyiértékű jegyét, akkor az így kapott szám
ismét prím. Megismételve ezt a rnűve Le t e t; ismét prímet kapunk, s ez folytatható egészen
addig, míg már csak egy egyjegyű számot vizsgálunk (természetesen ennek is prímnek kell
lenni) .
Ugyanez a tulajdonság igaz r á , ha az e Löbb i eljárást a legnagyobb helyiértékű
számjeggyel kezdjük. ( Az 1 számot nem tekintjük prímnek.)

Az INPUT file:
Soronként tartalmazza az egyes intervallumok megadását. Egy sor két természetes számot
tartalmaz (INTEGER tartományban), melyek közül a kisebb a kezdopont, a nagyobb a végpont.

Az OUTPUT file:
Soronként felsorolja az egyes intervallumokban található kívánt tulajdonságú számokat.
A kü l öribö zö intervallumokhoz tartozó számok között tartalmazzon egy üres sort. Ha az adott
intervallumban nincs megfelelo szám, akkor a NINCS szó szerepeljen annál az esetnél.

Samples:

INPUT OUTPUT

la 20 NINCS
15 30
23
27

Name: Gráf KLTE92 - 3

Files:
program c.pas
input c.inp
output c.out

Task:

A feladat olyan program írása, amely egy adott irányítatlan gráfban felderíti a
hurkokat, illetve megállapítja, hogya gráf hurokmentes. (Huroknak olyan utat nevezünk,
amelyen egy csúcsból elindulva, mindig különbözo éleken és csúcsokon haladva visszaérkezünk
a kiindulási csúcsba .)

Az INPUT file:
Tartalmazhat több gráf leírást is. Az egyes gráfleírásokat egy '*' karaktert
tartalmazó sor választja el egymástól. Egy gráf leírásánál az elso sor tartalmazza a csúcsok
számát, majd soronként az élek megadását a két csúcs sorszámával melyeket az él összeköt. A
csúcsokat természetes számokkal jelöl j ük , l-tol N-ig, ahol N a csúcsok száma (N < laO) (Két
csúcs között legfeljebb egy él van).

Az OUTPUT file:
Tartalmazza a hurkok leírását, minden hurkot kü l ön sorban adjon meg. Egy hurkot úgy
adjon meg, hogya legkisebb indexű csúcsból kiindulva valamely irányba haladva felsorolja a
hurkot alkotó csúcsokat (a kiindulásul vett csúcsot adjuk meg a sor elején és végén

56
is) .Illetve,ha a gráf hurokmentes, akkor a HUROKMENTES szó szerepeljen helyettük. A
különbözo gráfokhoz tartozó output adatokat egy üres sor válassza el egymástól.

Samples:

INPUT OUTPUT

5 HUROKMENTES
1 2

3 2 1 2 3 1

2 4 1 2 3 4 1

5 4 1 4 3 1

*
4

1 2

3 2
4 3
1 4

1 3

Name: Kocka KLTE92 - 4

Files:
program d.pas
input d.inp
output d.out

Task:

Tekintsünk egy kockát, melynek az lapjait az ábrán látható módon megszámoztuk.


Rendelkezésünkre áll három kü Löribö z ö s z i nü festék: kék (k), piros (p) és zöld lz). A kocka
mindegyik lapját befestjük a három szín valamelyikével.

+-5

4
3~ 2

Mivel a kockának 6 lapja van, a számozott lapú kockákat 729 féleképpen lehet
be fest eni . Ha azonban el tekintünk a lapok számozásától, akkor jóval kevesebb lehetoség
van,mivel a kockát a tengelyei körül el lehet forgatni. Az eredeti 7291ehetoség közül
azokat azonosnak tekintjük, melyeket t e t s z Leqe s
ö számú, alapokra me rö Laqe s , lapközépen
átmeno tengely körüli forgatások sorozatával át lehet vinni egymásba. (Tükrözés nem
megengedett)

Az INPUT file:
Minden sora 12 karaktert tartalmaz, az elso 6 karakter egy kocka színezését írja le az
ábra számozásának rne q f e Le Lö en , a második 6 karakter pedig egy másik kockát reprezentál. A
programnak el kell döntenie, hogy ez a két festési mód azonos-e az e l öbb í, értelemben vagy
sem.

57
Az OUTPUTfile:
Sorai tartalmazzák az input file sorainak megfelelo döntéseket, azaz a következo két
ítélet valamelyikét:
AZONOS,
NE:MAZONOS.

Samples:

INPUT OUTPUT

pkzzzppzzkzp AZONOS
pppkkkppkkkp NE:MAZONOS

Name: Szines gráf KLTE92 - 5

Files:
program e.pas
input e.inp
output e.out

Task:

Tekintsünk egy olyan irányítatlan összefüggo gráfot, amelynek minden élét befestettük
valamilyen színnel. A színek száma maximum négy (fekete, fehér, piros, kék).A feladat olyan
program írása, amely egy ilyen gráfban megkeresi a leghosszabb azonos s z nüí utat, azaz
éleknek olyan egymáshoz kapcsolódó láncolatát, amelyen végig tudunk úgy haladni, hogy egy
élen sem haladunk keresztül kétszer.

Az INPUT file:
A gráfok csúcspontj ai t természetes számokkal jelölj ük (N csúcspontú gráf esetében 1-

tol N-ig, N < 100). Az input file több gráf leírását is tartalmazhatja.E:gy gráfot úgy írunk
le, hogy az elso sorban megadjuk a csúcspontok számát, majd soronként közöljük az élek
leírását a köv e t e zö módon: i j fekete fehér ami azt jelenti, hogy az i és j sorszámú
csúcsokat egy fekete és egy fehér él köti össze. A kü l önböz ö gráfok megadását egy '*'
karaktert tartalmazó sor választja el egymástól.

Az OUTPUTfile
Eq y sora tartalmazza a leghosszabb eqys z nü í út hosszát, valamint azt hogy ez az út
milyen színu. A különbözo gráfokhoz tartozó válaszokat egy üres sor válassza el egymástól.

Samples:

INPUT OUTPUT

5 3 fehér
5 3 fehér 3 fehér
1 2 fehér 3 piros
2 3 fekete
2 4 fehér
5 fehér
*

58
6
1 2 fehér
2 3 piros
4 1 fehér
2 4 fehér
3 5 piros
6 5 piros
3 6 fehér kék

Name: Tanterem KLTE92 - 6

Files:
program f.pas
input f.inp
output f.out

Task:

A feladat olyan program írása, amely az órarendkészítés után a hallgatók változtatási


igényei t oldj a meg. Néhány csoport k pv i s e Lö j e
é találkozik, és mindenki közli, hogy melyik
idopontban melyik tantermet hány óra Ldö t a r t amr a tudj a felaj ánlani, s ennek fej ében mely
idopontra kér termet. Csak a felajánlott termekkel lehet gazdálkodni, más üres terem nincs.
Azt megengedj ü k, hogy egy többórás gyakorlat egyes óráit esetleg több kü Lö ribö z ő teremben
rendezzék ( Elso órát az egyik teremben, majd szünet után egy másik teremben). Az elso óra
8.00-kor ke zctöd.í k , s óránként jön a többi. Az összegyüj tött felaj ánlások és igények mindig
ugyanarra a napra vonatkoznak.

Az INPUT file:
Több eset leírását is tartalmazza, az egyes leírásokat egy '*' karaktert tartalmazó
sor választja el egymástól. Egy eset leírása a köv e t ke zö : Annyi sort tartalmaz, ahány
tanterem felajánlás van. Egy sor tartalmazza a gyakorlat kezdési idoponját (természetes szám
8-tói 16-ig, ebédszünet tel nem foglalkozunk), idotartamát órákban (1, 2, 3 vagy 4), helyét
(négykarakteres azonosító), s tartalmazza még azt az r döporit.o t, ahová a gyakorlatot tenni
szeretnék.

Az OUTPUTfile:
Tartalmazza azokat a tanterem cseréket amelyekkel a legtöbb igény kielégí t.he t ö • Egy
sor tartalmazza az azonos óraszámú gyakorlatokra vonatkozó cserét . Egy sorban legyenek azok
a cserék is, amikor egy hosszabb foglalkozás helyére több rövidebbet cserélnek, vagy több
rövidebb helyére egy hosszabbat. A különbözo esetekhez tartozó input adatokat egy üres sor
válassza el egymástól.

Samples:

INPUT OUTPUT

8 1 M105 9 M105 -> M106


9 1 M106 8 M106 -> M105

*
8 1 M105 10 M105,M203 -> M302
9 1 M203 II M302 -> M105,M203
10 2 M302 8

59
Name: Szállítás KLTE92 - 7

Files:
program g.pas
input g.inp
output g.out

Task:

Adott R raksúlyú teherautóval el akarunk szállítani az A pontból a B pontba n db


tovább nem osztható csomagot, melyeknek súlyai sl, s2, s3, sn. A feladat olyan
program írása, amely meghatározza, hogy mennyi az a legkevesebb számú forduló, amellyel el
lehet szállítani a csomagokat.

Az INPUT file:
Egy esetet egy sorban ír le, a következö formában: R sl s2 s3 ... sn (n < 100). Több
esetet is tartalmazhat, ezeket az input file egymás után következö sorai írják le.

Az OUTPUT file : IG.OUTI


Soronként tartalmazza a megfelelö esethez tartozó minimális fordu1ószámot.

Samples:

I INPUT

10 1 1 2 5 8 9

Name: Permalex RUGB92 1

Files:
program a.pas
input a.inp
output a.out

Task:

Given a string of characters, we can permute the individual characters to make new
strings If we can impose an ordering on the characters (say alphabetic sequence), then the
strings themsel ves can be ordered and any gi ven permutation can be gi ven a unique number
designating its posi tion in that ordering . For example the string 'acab' gi ves rise to the
following 12 distinct permutations:

aabc 1 acab 5 bcaa 9


aacb 2 acba 6 caah 10
abac 3 baac 7 caba II
abca 4 baca 8 cbaa 12

Thus the string 'aeab' can be characterized in this sequence as 5.

Write a program that will read in a string and determine its position in the ordered
sequence of permutations of its constituent characters. Note that numbers of permutations
can get very large; however we guarantee that no string will be given whose position is more
than 2~31-1 = 2,147,483,647.

60
Input will consist of series of lines, each line containing one string. Each string
will consist of up to 30 lower case letters, not necessarily distinct. The file will be
terminated by a line consisting of a single #

Output will consist of a series of lines, one for each line of the input. Each line
will consist of the position of the string in its sequence, right justified in a field of
width 10.

Samples:

INPUT OUTPUT

bacaa 15
abc 1
cba 6
#

Name: Caesar Cypher RUGB92 2

Files:
program b.pas
input b.inp
output b.out

Task:

One of the earliest encrypting systems is attributed to Julius Caesar: if the letter
to be encrypted is the Nth letter in the alphabet, replace it with the (N+K)th where K is
some fixed integer (Caesar used K=3). We usually treat a space as zero and all arithmetic is
then done modulo 27. Thus for K = 1 the message 'ATTACK AT DAWN' becomes 'BUUBDLABUAEBXO'
Decrypting such a message is trivial since one only needs to try 26 different values
of K. This process is aided by knowledge of the language, since then one can determine when
the decrypted text forms recognizable words. If one does not know the language, then a
dictionary would be necessary.
Write a program that will read' in a dictionary and some encrypted text, determine the
value of K that was used, and then decrypt the cyphertext to produce the original message.
The original message contained only letters and spaces and has been encrypted using the
above method. The most suitable value of K will be the one which produces the most matches
with the words in the dictionary.

Input will consist of a dictionary and the encrypted text. The dictionary will consist
of no more than 100 lines each containing a word in upper case characters and not more than
20 characters in length. The dictionary portion will be terminated by a line consisting of a
single #. The encrypted text will follow immediately and will consist of a single line
containing no more than 250 characters. Note that the dictionary will not necessarily
contain all the words in the original text, although it will certain1y contain a large
proportion of them. It may also contain words that are not in the original text. The
dictionary will not appear in any particular order.

Output will consist of the decrypted text. Lines should be as long as possible, but
not exceeding 60 characters and no word may cross a line break.

61
Samples:

INPUT OUTPUT

THIS ATTACK ZORRO AT DAWN


DAWN
THAT
THE
ZORRO
OTHER
AT
THING

BUUBDLA PSSPABUAEBXO

Name: Orchard Trees RUGB92 3

Files:
program c.pas
input c.inp
output c.out

Task:

An Orchardist has planted an orchard in a rectangle with trees uniformly spaced in


both directions. Thus the trees form a rectangular grid and we can consider the trees to
have integer coordinates. The origin of the coordinate system is at the bottom left of the
following diagram:

• • • • • • • • • • • • •
• • • • • • • • • • •
• • • • • • • • • • •
• • • • • • • • • •
• • • • • • • • • • •
• • • • • • • • • • • • •
Consider that we now overlay a series of triangles on to this grid. The vertices of
the triangle can have any real coordinates in the range 0.0 to 100.0, thus trees can have
coordinates in the range 1 to 99. Two possible triangles are shown.

Wri te a program that will determine how many trees are contained wi thin a gi ven
triangle. For the purposes of this problem, you may assume that the trees are of point size,
and that any tree (point) lying exactly on the border of a triangle is considered to be in
the triangle.

62
Input will consist of a series of lines. Each line will contain 6 real numbers in the
range 0.00 to 100.00 representing the coordinates of a triangle . The entire file will be
terminated by a line containing 6 zeroes (O O O O O O).

Output will consist of one line for each triangle, containing the number of trees for
that triangle right justified in a field of width 4.

Samples:

INPUT OUTPUT

1.5 1.5 1.5 6.8 6.8 1.5 15


10.7 6.9 8.5 1.5 14.5 1.5 17
O O O O O O

Name: Bandwidth RUGB92 4

Files:
program d.pas
input d.inp
output d.out

Task:

Given a graph (V,E) where V is a set of nodes and E _is a set of ares in VxV, and an
ordering on the elements in V, then the bandwidth of a node v is defined as the maximum
distance in the ordering between v and any node to which it is; connected in the graph. The
bandwidth of the ordering is then defined as the maximum of the indi vidual bandwidths. for
example, consider the following graph:

..=-----/~./í
B G H
I
E

C D
This can be ordered in many ways, two of which are illustrated below:

I /'------.1 I
l--~--c--D -- E -- H --~ A --- B ---C --O G --F H --E
,---1 1 1 1

for these orderings, the bandwidths of the nodes (in order) are 6, 6, 1, 4, 1, 1, 6, 6
giving an ordering bandwidth of 6, and 5, 3, 1, 4, 3, 5, 1. 4 giving an ordering bandwidth
of 5
Write a program that will find the ordering of a graph that minimizes the bandwidth.
Input will consist of a series of graphs. Each graph will appear on a line by itself,
The entire file will be terminated by a line consisting of a single *. for each graph, the
input will consist of a series of records separated by ';' Each record will consist of a

63
node name (a single upper case character in the range 'A' to 'Z'), followed by a and at
least one of its neighbor. The graph will contain no more than 8 nodes

Output will consist of one line for each graph, listing the ordering of the nodes
followed by an arrow (-» and the bandwidth for that ordering. All items must be separated
from their neighbors by exactly one space. If more than one ordering produces the same
bandwidth, then choose the smallest in lexicographic ordering, that is the one that would
appear first in an alphabetic listing.

Samples:

INPUT OUTPUT

A:FB;B:GC;D:GC;F:AGH;E:HD A B C F G D H E -> 3
#

Name: Bridge Hands RUGB92 5

Files:
program e.pas
input e.inp
output e.out

Task:

Many games, such as Bridge, involve dealing a standard deck of 52 cards to 4 players,
so that each receives 13 cards. Good players can then play with the hand as it is dealt, but
most ordinary players will need to sort it, firstly by suit, and then by rank within suit.
There is no fixed ranking of the suits for this purpose, but it is useful to alternate the
colours, so we will presume the following ordering: •••< • < '" < • INote that because most
character sets do not recognize these symbols, from now on we will use the more
conventional C, O, S, H). Within a suit, Ace is high, so the ordering is 2 < 3 < 4 < 5 <
6<7<B<9<T<J<Q<K<A. The players are usually designated North, South, East and West, and they
si t at the points of the compass they name. One player is designated the dealer and she
deals one card to each player starting with the player on her left and proceeding clockwise
until she deals the last card to herself.
S -> W -> N -> E -> S -> ....
Write a program that will read in a representation of a deck of cards, deal them, sort
them, and then display the 4 sorted hands in the format shown below

Input will consist of a series of deals. Each deal will consist of the letter
representing the dealer IN, E, S, W) followed by two lines representing the deck as shown
below. The file will be terminated by a line consisting of a single #.

Output will consist of a series of sets of four lines, one set for each deal. Each set
will consist of four lines displaying the sorted hands, in the order and format shown below.
Sets must follow each other immediately, with no blank line between them.

64
Samples:

INPUT OUTPUT

N s: C3 cs C7 CT CJ D9 DT DJ S3 SK H2 H9 HT

CQDTC4D8S7HTDAH7D2S3D6C6S6D9S4SAD7H2CKHSD3CTS8C9H3C3 W: C2 C4 CK D4 DS D6 DQ DA S4 S8 ST SJ H8

DQS9SQDJH8HAS2SKD4H4SSC7SJC8DKCSC2CAHQCJSTH6HKH9DSHJ N: C6 C8 C9 CA D8 S9 SA H4 HS H6 H7 HJ HA

E: CQ D2 D3 D7 DK S2 SS S6 S7 SQ R3 HQ HK

Name: Student Grants RUGB92 6

Files:
program f.pas
input f.inp
output f.out

Task:

The Government of Impecunia has decided to discourage tertiary students by making the
payments of tertiary grants a long and time-consuming process. Each student is issued a
student ID card which has a magnetically encoded strip on the back which records the payment
of the student grant. This is initially set to zero. The grant has been set at 40$ per year
and is paid to the student on the working day nearest to his birthday. (Impecunian society
is still somewhat medieval and only males continue with tertiary education.) Thus on a any
given working day up to 25 students will appear at the nea rest office of the Department of
Student Subsidies to collect their grant.
The grant is paid by an Automatic Teller Machine which is driven by a reprogrammed
8085+1/2 chip originally designed to run the state slot machine. The ATM was built in the
State workshops and is designed to be directly to rob. It consists of an interior vault
where it holds a large stock of $1 coins and an output store from which these coins are
dispensed. To limit possible losses it will only move coins from the vault to the output
store when that is empty. When the machine is switched on in the morning, wi th an empty
output store; it immediately moves 1 coin into the output store. When that has be en
dispensed it will then move 2 coins, then 3, and so on until it reaches some preset limit k.
It then recycles back to 1, then 2 and so on.
The students form a queue at this machine and, in turn, each student inserts his card.
The machine dispenses what it has its output store and updates the amount paid to that
student by writing the new total on the card. If the student has not received his full
grant, he remaves his card and rejoins the queue at the end. If the amount in the store plus
what the student has already recei ved comes to more than 40$, the machine only pays aut
enough to make the total up to $40. Since this fact is recorded on the card, it is pointless
for the student to continue queuing and he leaves. The amount remaining in the store is the
available for the next student.
Write a: program that will read in values of N (the number of students, 1 < N < 25)
and k (the limit for that machine, 1 < k < 40) and calculate the order in which the students
leave the queue.
Input will consist of a series of lines each containing a value for N and k as
integers. The list will be terminated by two zeroes (O O.
Output will consist of a line for each line input and will contain the list of
students in the order in which they leave the queue. Students are ordered according to their
position in the at the start of the day. AlI numbers must be right justified in a field of
width 3.

65
Samples:

I INPUT I OUTPUT
5 3 l 3 5 2
O O

Name: Amazing RUGB92 7

Files:
program g.pas
input g.inp
output g.out

Task:

One of the apparently intelligent tricks that enthusiastic psychologists persuade mice
to perform is solving a maze. There is still some controversy as to the exact strategies
employed by the mice when engaged in such a task, but it has been claimed that the animaI
keepers eavesdropping on conversations between the mice have heard them say things like "1
have finally got Dr Schmidt trained. Every time 1 get through the maze he gives me food".
Thus when autonomous robots were first being built, it was decided that solving such
mazes would be a good test of the 'intelligence' built into such machines by their
designers. However, to their chagrin, the first contest was won by a robot that placed a
sensor on the right hand wall of the maze and sped through the maze maintaining contact with
the right hand wall at alI times. This led to a change in the design of the mazes, and also
to interest in the behavior of such robots. To test this behavior the mazes were modified to
be come closed boxes with internal walls. The robot was placed in the south west corner and
set off pointing east. The robot then moved through the maze keeping a wall on its right at
alI times. If it cannot proceed it will turn left until it can proceed. AlI turns are exact
right angles. The robot stops when it returns to the starting square. The mazes were always
set up so that the robot could move to at least one other square before returning. The
researchers then determined how many squares were not visi ted, and how many were visi ted
once, twice, thrice and four times. AlI square is visited if a robot moves into and out of
it. Thus for the following maze, the values (in order) are: 2, 3, 5, 1, O .

values.
Wri te a program to
••
simulate the behavior of such a robot and collect the desired

Input will consist of a series of maze descriptions. Each maze description will start
with a line containing two integers representing the size of the maze (b and w). This will
be followed by b lines, each consisting of w characters, either "O" or "1". Ones represent
closed squares, zeroes represent open squares. Since the maze is enclosed, the outer wall is
not specified. The file will be terminated by a line containing two zeroes.

66
Output will consist of a series of lines, one for each maze. Each line will consist of
5 integers representing the desired values, each value right justified in a field of width
3.

Samples:

INPUT OUTPUT

3 5 2 351 O
01010
01010
00000
O O

Name: Ali Squares RUGB92 8

Files:
program h.pas
input h.inp
output h.out

Task:

Geometrically, any square has a unique, well-defined center point. On a grid this is
on true if the sides of the square are an add number of points long. Since any add numb can
be written in the form 2k+1, we can characterize any such square by specifying that is we
can say that a square whose sides are of length 2k+1 has size k . Now define patt ern of
squares as follaws.
1. The largest square is of size k (that is sides are of length 2k+1) and is centered
in grid of size 1024 (that is the grid sides are of length 2049).
2. The smallest permissible square is of size 1 and the largest is of size 512, the
1<k<512.
3. All squares of size k > 1 have a square of size k div. 2 centred on each of their
corners. (Div implies integer division, thus 9 di v 2 = 4).
4. The top left corner of the screen has coordinates (O, O), the bottom right has
coordinates (2048, 2048).
Hence, given a value of k, we can draw a unique pattern of squares according to the
above rules. Furthermore any point on the screen will be surrounded by zero or more squares.
(If the point is on the border of a square, it is considered to be surrounded by that
square). Thus if the size of the largest square is given as 15, then the follawing pattern
would be produced.

67
/,}, ..~
'

Write a program that will read in a value of k and the coordinates of a point, and w
determine how many squares surround the point.
Input will consist of a series of lines. Each line will consist of a value of k and
the coordinates of a point. The file will be terminated by a line consisting of three zeroes
(O O O)
Output will consist of a series of lines, one for each line of the input. Each line
will consist of the number of squares containing the specified point, right justified in a
field of width 3.

Samples:

941

Name: Spreadsheet ACMF92 - 1


Calculator

Files:
program a.pas
input a.inp
output a.out

Task:

A spreadsheet is a rectangular array of cells. Cells contain data or expressions that


can be evaluated to obtain data. A 'simple' spreadsheet is one in which data are integers
and expressions are mixed sums and differences of integers and cell references. For any
expression, if each cell that is referenced contains an integer, then the express ion can be

68
replaced by the integer to which the express ion evaluates. You are to write a program which
evaluates simple spreadsheets.
Input
Input consists of a sequence of simple spreadsheets. Each spreadsheet begins with a
line specifying the number of rows and the number of columns. No spreadsheet contains more
than 20 rows or 10 columns. Rows are labeled by capital letters A through T. Columns are
labeled by decimal digits O through 9. Therefore, the cell in the first row and first
column is referenced as AO; the cell in the twentieth row and fifth column is referenced as
T4.
Following the specification of the number of rows and columns is one line of data for
each cell, presented in row-major order. (That is, all cells for the first row come first,
followed by all cells for the second row, etc.) Each cell ini ti al ly contains a signed
integer value or an express ion involving unsigned integer constants, cell references, and
the operators + (addition) and (subtraction). If a cell initially contains a signed
integer, the corresponding input line will begin with an optional minus sign followed by
one or more decimal digits. If a cell initially contains an expression, its input line will
contain one or more cell references or unsigned integer constants separated from each other
by + and - signs. Such a line must begin with a cell reference. No expression contains more
than 75 characters. No line of input contains leading blanks. No express ion contains any
embedded blanks. However, any line may contain trailing blanks.
The end of the sequence of spreadsheets is marked by a line specifying O rows and O
columns.
Output
For each spreadsheet in the input, you are to determine the value of each expression
and display the resulting spreadsheet as a rectangular array of numbers with the rows and
columns appropriately labeled. In each display, all numbers for a column must appear right-
justified and aligned with the column label. Operators are evaluated left to right in each
expression; values in cells are always less than 10000 in absolute value. Since
expressions may re ference cells that themselves contain expressions, the order in which
cells are evaluated is dependent on the expressions themselves.
If one or more cells in a spreadsheet contain expressions with circular references,
then the output for that spreadsheet should contain only a list of the unevaluated cells in
row-major order, one per line, with each line containing the cell label, a colon, ablank,
and the cell's original expression.
A blank line should appear following the output for each spreadsheet.

Name: Getting in Line ACMF92 2

Files:
program b.pas
input b.inp
output b.out

Task:

Computer networking requires that the computers in the network be linked. This
problem considers a 'linear' network in which the computers are chained together so that
each is connected to exactly two others except for the two computers on the ends of the
chain which are connected to only one other computer. A picture is shown below. Here the
computers are the black dots and their locations in the network are identified by planar
coordinates (relative to a coordinate system not shown in the picture). Distances between
linked computers in the network are shown in feet.

69
(8.16) (12,16)

5 ft. 13.42 ft.

(8.11)
(24.10)
'1.18ft
(13,8)

For various reasons it is desirable to minimize the length of cable used. Your problem is
to determine how the computers should be connected into such a chain to minimize the total
amount of cable needed. In the installation being constructed, the cabling will run beneath
the floor, so the amount of cable used to join 2 adjacent computers on the network will be
equal to the distance between the computers plus 16 additional feet of cab1e to connect
from the floor to the computers and provide some slack for ease of installation.
The picture below shows the optimal way of connecting the computers shown above, and
the total length of cable required for this configuration is (4+16)+ (5+16) + (5.83+16) +
(11.18+16) = 90.01 feet.

4 ft.
(8.16) (12.16)

Total length of cable needed = 90.01 ft.

(24.10}

(13.8)

Input
The input file will consist of a series of data sets. Each data set will begin with a
line consisting of a single number indicating the number of computers in a network. Each
network has at least 2 and at most 8 computers. A va1ue of O for the number of computers
indicates the end of input. After the initial line in a data set specifying the number of
computers in a network, each additional line in the data set will give the coordinates of a
computer in the network. These coordinates will be integers in the range O to 150. No two
computers are at identical locations and each computer will be listed once.

Output
The output for each network should include a line which telis the number of the
network (as determined by its position in the input data), and one line for each length of
cable to be cut to connect each adjacent pair of computers in the network. The final line
should be a sentence indicating the total amount of cable used. In listing the lengths of
cab1e to be cut, traverse the network from one end to the other. (It makes no difference at
which end you start.) Use a format similar to the one shown in the sample output, with a

70
line of asterisks separating output for different networks and with distances in fe et
printed to 2 decimal places.

Samples:

INPUT OUTPUT

6 Network \#1
5 19 Cable requirement to connect (5,19 ) to (55,28) is 66.80 feet.
55 28 Cable requirement to connect (55,28) to (28,62 ) is 59.42 feet.
38 101 Cable requirement ta connect (28,62 ) to (38,101) is 56.26 feet.
28 62 Cable requirement to connect (38,101) to (43,116) is 31. 81 feet.
111 84 Cable requirement to connect (43,116) to (111,84) is 91.15 feet.
43 116 Number of feet of cable required is 305.45.
*******************************************************************
5 Network \#2
11 27 Cable requirement to connect (11,27) to (88,30) is 93.06 feet.
84 99 Cable requirement to connect (88,30) to (95,38) is 26.63 feet.
142 81 Cable requirement to connect (95,38) to (84,99 ) is 77.98 feet.
88 30 Cable requirement to connect (84,99 ) to (142,81) is 76.73 feet.
95 38 Number of feet of cable required is 274.40.
*********************************************************************
3 Network \#3
132 73 Cable requirement to connect (132,73) to (72,111) is 87.02 feet.
49 86 Cable requirement to connect (72,111) to (49,86 ) is 49.97 feet.
72 111 Number of feet of cable required is 136.99.
O

Name: Radio Direction ACMF92 3


Finder

Files:
program c.pas
input c.inp
output C.out

Task:

A boat with a directional antenna can determine its present position with the help of
readings from local beacons. Each beacon is located at a known position and emits a unique
signal. When a boat detects a signal, it rotates its antenna until the signal is at maximal
strength. This gi ves a relative bearing to the posi tion of the beacon. Gi ven a previous
beacon reading (the time, the relative bearing, and the position of the beacon), a new
beacon reading is usually sufficient to determine the boat's present position. You are to
write a program to determine, when possible, boat positions from pairs of beacon readings.
For this problem, the posi tions of beacons and boats are relative to a rectangular
coordinate system. The positive x-axis points east; the positive y-axis points north. The
course is the direction of travel of the boat and is measured in degrees clockwise from
north. That is, north is 0i, east is 90i, south is 180i, and west is 270i The relative
bearing of a beacon is given in degrees clockwise relative to the course of the boat. A
boat's antenna cannot indicate on which side the beacon is located. A relative bearing of
90i means that the beacon is toward 90i or 270i.

Input

71
The first line of input is an integer specifying the number of beacons (at most 30).
Following that is a line for each beacon. Each of those lines begins with the beacon's name
(a string of 20 or fewer alphabetic characters), the x-coordinate of its position, and the
y-coordinate of its position. These fields are single-space separated.
Coming after the lines of beacon information is an integer specifying a number of
boat scenarios to follow. A boat scenario consists of three lines, one for velocity and two
for beacon readings.

Data on input line Meaning of data


course speed the boat's course, the speed at which it is traveling
time#l name#l angle#l time of first beacon reading, name of first beacon, relative
bearing of first beacon
time#2 name#2 angle#2 time of second reading, name of second beacon, relative
bearing of second beacon

All times are given in minutes since midnight measured over a single 24-hour period.
The speed is the distance (in uni ts matching those on the rectangular coordinate system)
over time. The second line of a scenario gives the first beacon reading as the time of the
reading (an integer), the name of the beacon, and the angle of the reading as measured from
the boat's course. These 3 fields have single space separators. The third line gives the
second beacon reading. The time for that reading will always be at least as large as the
time for the first reading.

Output
For each scenario, your program should print the scenario number (Scenario 1,
Scenario 2, etc.) and a message indicating the posi tion (rounded to 2 decimal places) of
the boat as of the time of the second beacon reading. If it is impossible to determine the
position of the boat, the message should say 'Position cannot be determined.'

Name: Moth Eradication ACMF92 4

Files:
program d.pas
input d.inp
output d.out

Task:

Entomologists in the Northeast have set out traps to determine the influx of Jolliet
moths into the area. They plan to study eradication programs that have some potential to
control the spread of the moth population. The study calls for organizing the traps in which
moths have been caught into compact regions, which will then be used to test each
eradication program. A reg ion is defined as the polygon with the minimum length perimeter
that can enclose all traps within that region. For example, the traps (represented by dots)
of a particular region and its associated polygon are illustrated below.

72
You must write a program that can take as input the locations of traps in a region
and output the locations of traps that lie on the perimeter of the region as weil as the
length of the perimeter.

Input
The input file will contain records of data for several regions. The first line of
each record contains the number (an integer) of traps for that region. Subsequent lines of
the record contain 2 real numbers that are the x- and y-coordinates of the trap locations.
Data within a single record will not be duplicated. End of input is indicated by a region
with O traps.

Output
Output for a single region is displayed on at least 3 lines:

First line: The number of the region. (The first record corresponds to region #1,
the second to region #2, etc.)
Next 1ine(s): A listing of a11 the points that appear on the perimeter of the
region. The points must be identified in the standard form '(x-
coordinate,y- coordinate)' rounded to a single decimal place. The starting
point for this listing is irrelevant, but the listing must be oriented
clockwise and begin and end with the same point. For
collinear points, any order which describes the minimum length perimeter is
acceptable.
Last line: The length of the perimeter of the region rounded to 2 decimal p1aces.
One blank line must separate output from consecutive input records.

A sample input file with records for 3 regions followed by correct output for the
sample input is shown on the reverse.

Samples:

INPUT OUTPUT

3 Region #1
1 2 (1.0,2.0)-(4.0,10.0)-(5.0,12.3)-(1.0,2.0)
4 10 Perimeter length = 22.10
5 12.3

73
6 Region #2:
O O (O.O, O. O) - (3. 0,4.5) - (6. 0,2.1) - (2.O, -3.2)-
1 1 (0.0,0.0)
3.1 1.3 Perimeter length 19.66
3 4.5
6 2.1 Region #3:
2 -3.2 (O. O, O. O) - (2.0,2. O) - (4. 0,1. 5) - (5. O, O. 0)-
7 (2.5,-1.5)-(0.0,0. O)

1 0.5 Perimeter length = 12.52


5 O
4 1.5
3 -0.2
2.5 -1.5
O O
2 2
O

Name: Department of ACMF92 5


Redundancy
Department

Files:
program e.pas
input e.inp
output e.out

Task:

When designing tables for a relational database, a functiona1 dependency (FO) is used
to express the relationship between the di fferent fields. A functional dependency is
concerned with the relationship of values of one set of fie1ds to those of another set of
fields. The notation X->Y is used to denote that when supplied va1ues to the field (s) in
set X, the assigned value for each field in set Y can be determined. For example, if a
database table is to contain fie1ds for the social security number (S), name (N) , address
(A), and phone (P) and each person has been assigned a unique value for S, the S field
functionally determines the N, A and P fields. This is written as S->NAP.
Oevelop a program that will identify each redundant FO in each input group of FOs. An
FO is redundant if it can be derived using other FOs in the group. For example, if the
group contains the FOs A->B, B->C, and A->C, then the third FO is redundant since the field
set C can be derived using the first two. (The A fields determine values for the B fields,
which in turn determine values for the fields in C.) In the group A->B, B->C, C->A, A->C,
C->B, and B->A, all the FOs are redundant.
Input
The input file contains an arbitrary number of groups of FOs. Each group is preceded
by a line containing an integer no larger than 100 specifying the number of FOs in that
group. A group with zero FOs indicates the end of the input. Each FO in the group appears
on a separate line containing two non- empty lists of field names separated by the
characters - and >. The lists of fie1d names contain only uppercase alphabetic characters.
Functiona1 dependency lines contain no b1anks or tabs. There are no tri vially redundant
FOs (for examp1e, A->A). For identification purposes, groups are numbered sequentiaIly,
starting with 1; the FOs are also numbered sequentia11y, starting with 1 in each group.
Output
For each group, in order, your program must identify the group, each redundant FO in
the group, and a sequence of the other FOs in the group which were used to determine the
indicated FO is redundant. If more than one sequence of FOs can be used to show another FO

74
is redundant, any such sequence is acceptable, even if it is not the shortest proof
sequence. Bach FD in an acceptable proof sequence must, however, be necessary. If a group
of FDs contains no redundancy, display No redundant FDs.

Name: Othello ACMF92 6

Files:
program f.pas
input f.inp
output f.out

Task:

Othello is a game played by two people on an 8 x 8 board, using disks that are white
on one side and black on the other. One player places disks with the white side up and the
other player places disks with the black side up. The players alternate placing one disk on
an unoccupied space on the board. In placing a disk, the player must bracket at least one
of the other color disks. Disks are bracketed if they are in a straight line horizontally,
verticaIly, or diagonally, with a disk of the current player's color at each end of the
line. When a move is made, alI the disks that were bracketed are changed to the color of
the player making the move. (It is possible that disks will be bracketed across more than
one line in a single move.)
Write a program to read a series of Othello games. The first line of the input is the
number of games to be processed. Bach game consists of a board configuration followed by a
list of commands. The board configuration consists of 9 lines. The first 8 specify the
current state of the board. Bach of these 8 lines contains 8 characters, and each of these
characters will be one of the following:
, indicating an unoccupied square
'B' indicating a square occupied by a black disk
'W' indicating a square occupied by a white disk

The ninth line is either a 'B' or a 'W' to indicate which is the current player. You
may assume that the data is legally formatted.
The commands are to list alI possible moves for the current player, make a move, or
quit the current game. There is one command per line with no blanks in the input. Commands
are formatted as follows:
List a Ll, possible moves for the current player. The command is an 'L' in the first
column of the line. The program should go through the board and print alI legal moves for
the current player in the format (x,y) where x represents the row of the legal move and y
represents its column. These moves should be printed in row major order which means:
1) alI legal moves in row number i will be printed before any legal
move in row number j if j is greater than i
and
2) if there is more than one legal move in row number i, the moves will be
printed in ascending order based on column number.

AlI legal moves should be put on one line. If there is no legal move because it is
impossible for the current player to bracket any pieces, the program should print the
message 'No legal move.'
Make a move. The command is an 'M' in the first column of the line, followed by 2
digits in the second and third column of the line. The digits are the row and the column of
the space to place the piece of the current player's color, unless the current player has
no legal move. If the current player has no legal move, the current player is first changed
to the other player and the move will be the move of the new current player. You may assume
that the move is then legal. You should record the changes to the board, including adding
the new piece and changing the color of alI bracketed pieces. At the end of the move, print

75
the number of pieces of each color on the board in the format 'Black - xx White - yy' where
xx is the number of black pieces on the board and yy is the number of white pieces on the
board. After a move, the current player will be changed to the player that did not move.
Quit the current game. The command will be a 'Q' in the first column of the line. At
this point, print the final board configuration using the same format as was used in the
input. This terminates input for the current game.
You may assume that the commands will be syntactically correct. Put one blank line
between output from separate games and no blank lines anywhere else in the output.

Name: Urban Elevations ACMF92 - 7

Files:
program g.pas
input g.inp
output g.aut

Task:

An elevation of a collection of buildings is an orthogonal projection of the


buildings onto a vertical plane. An external elevation of a city would show the skyline and
the faces of the 'visible' buildings of the city as viewed from outside the city from a
certain direction. A southern elevation shows no sides; it shows the perfectly rectangular
faces of buildings or parts of faces of buildings not obstructed on the south by taller
buildings. For this problem, you must wri te a program that determines which buildings of a
city are visible in a southern elevation.
For simplicity, assume a LL the buildings for the elevation are perfect rectangular
solids, each with two sides that run directly east-west and two running directly north-
south. Your program will find the buildings that appear in a southern elevation based on
knowing the positions and heights of each city building. That data can be illustrated by a
map of the city as in the diagram on the left below. The southern elevation for that city
is illustrated in the diagram on the right.

LJ
9
1 801
50 ~35

o
4

III
D
~ ~ 25
30 1 14
[;]
lS 80 I
90 110
[;J
501
~ 30 5 9 4 3 10 2
"
Input
Input for your program consists of the numeric description of maps of several cities.
The first line of each map contains the number of buildings in the ci ty (a non-negati ve
integer less than 101). Each subsequent line of a map contains data for a single building N
5 real numbers separated by spaces in the following order:
x-coordinate of the southwest corner
y-coordinate of the southwest corner
width of the building (length of the south side)
depth of the building (length of the west side)
height of the building
Each map is oriented on a rectangular coordinate system so that the positive x-axis
points east and the positive y-axis points north. Assume that a II input for each map

76
corresponds to a legitimate map (the number of buildings is the same as the number of
subsequent lines of input for the map; no two buildings in a single map overlap). Input is
terminated by the number O representing a map with no buildings.
Output
Buildings are numbered according to where their data lines appear in the map's input
data N building #1 corresponding to the first line of building data, building #2 data to
the next line, and building #n to the nth line of building data for that map. (Buildings on
subsequent maps also begin their numbering wi th 1.) For each map, output begins wi th line
identifying the map (map #1, map #2, etc.) On the next line the numbers of the visible
buildings as they appear in the southern elevation, ordered south-to-north, west-to-east.
This means that if building n and building m are visible buildings and if the southwest
corner of building n is west of the southwest corner of building m , then number n is
printed before number m. If building n and building m have the same x-coordinate for their
southwest corners and if building n is south of building m, then the number n is printed
before the number m. For this program, a building is considered visible whenever the part
of its southern face that appears in the elevation has strictly positi ve area. One blank
line must separate output from consecutive input records

Samples:

INPUT OUTPUT

160 O 30 60 30 map #1
125 O 32 28 60 5 9 4 3 10 2 1 14
95 O 27 28 40
70 35 19 55 90
O O 60 35 80
O 40 29 20 60
35 40 25 45 80
O 67 25 20 50
O 92 90 2 O 8 O
95 38 55 12 50
95 60 60 13 30
95 80 45 25 50
165 65 15 15 25
165 85 10 15 35
O

Name: Urban Elevation KLTE93 - 1

Files:
program urban.pas
input urban.inp
output urban.out

See ACMF92-7

Name: Moth Eradiction KLTE93 - 2

Files:
program moth.pas
input moth.inp
output moth.out

See ACMF92-4

77
Name: Getting in Line KLTE93 - 3

Files:
program line.pas
input line.inp
output line.out

See ACMF92-2

Name: Fibonacci Loops KLTE93 - 4

Files:
program loops.pas
input loops.inp
output loops.out

Task:

A Fibonacci loop is a set of three numeric vectors that has a particular property. It
is best described by an example:

Fl: (6730011101)
F2: (7621011101)
F3: (5911002200)

The ith position of each vector (starting from zero) represents a tally of the number
of occurrences of i in the other two vectors. In this example, the '6' in Fl indicates a
total of 6 zeroes in F2 and F3. Similarly, the '9' in F3 indicates a total of 9 ones in Fl
and F2. Sach vector in the set describes the union of the other two vectors. Wri te a
program to read in pairs of vectors. The numbers within the vector pairs will be separated
from each other by one or more spaces. The value of any number in any vector will not exceed
the number of elements in that vector. A vector will be contained on a single line, less
than 80 characters in length. The input will be terminated by end-of file. If the pair of
vectors are of the same length, compute the third vector that describes the vector pair.
Determine if the entire set is a Fibonacci loop (Fl describes F2 and F3, F2 describes Fl
and F3, and F3 describes Fl and F2. Print the vector sets in formatted columns similar to
the sample output. Print one of the following messages to describe the set:

'A valid Fibonacci loop.'


'Invalid solution.'
'Vectors are of different sizes.'

Skip a line between sets.

78
Samples:

INPUT OUTPUT

6 6 2 2 O 2 O 2 O O 6 6 2 2020200
7 3 5 1 O 1 2 1 O O 7 3 5 1 O 1 2 100
7 6 2 1 O 1 1 1 1 7 3 5 1 O 1 2 100
5 8 1 1 O O 2 2 1 A valid Fibonacci loop.
6 7 3 O O l 1 l O
7 6 2 l O l l l O 1 7 6 2 1 011 1 1
3 O 3 2 2 5 8 1 1 O O 2 2 1
2 O 4 4 O 3 8 3 O O 1 1 1 1
Invalid solution.

673001 110
7 6 2 1 O i 1 101
Vectors are of different sizes.

3 2 3 2 2
2 O 4 4 O
3 O 3 2 2
A valid Fibonacci loop.

Name: Fractured Fraction KLTE93 - 5

Files:
program fract.pas
input fract.inp
output fract.out

Task:

A fractured fraction is a special form that includes a continued fraction in which


only single-digit, positive integers appear and no digit (except 1) appears more than once.
Examples of fractured fractions are:

71 1
9 1
25 1 ' 29 1
1+-- 3+--
1 1
5+- 4+-
4 2

Develop a program that determines whether a given standard fraction can be represented
as a fractured fraction. If a fractured fraction representation exists, a pretty-printed
version of the fractured fraction should be produced. To pretty print a fractured fraction:

-fraction bars are printed as a series of hyphen (minus signi characters,


-alI numerators and denominators must be centered with respect to
then fraction bars,
-alI plus signs must be preceded and followed by exactly one
space,
-the fraction bar of the final fraction consists of exactly three hyphen
characters,

79
-the fraction must begin at the left margin,
-the entire fraction must be justified on the right.

The program must handie any fraction which can be represented as a fractured fraction,
including fractions which are not in lowest terms and improper fractions. Improper fractions
which reduce to single digit integers are to be considered valid fractured fractions as are
fractions such as one-hal f, one-third, etc.

Input
The input data for this program consists of a series of fractions, one per
data line in the following format:
numerator denominator
where both input values are integers separated by at least one space. The input will
be terminated by end-of file.

Output
The output of this program will consist of a pretty-printed fractured fraction for all
fractions which can be legitimately represented as fractured fractions, or the following
error message:
NO FRACTURED FORM: numerator / denominator$ - Issued when the input fra ct ion cannot
be represented as a fractured fraction.
You may assume that no fractured fra ct ion will contain a line in excess of 80
characters in length. The results of processing each input fraction should be separated by
two blank lines in your output.

Samples:

INPUT OUTPUT

71 25 1
5 O 2 + ---------
3 5 1
12 3 1 + -----

3 12 1
8 -ll 5 + ---
21814 6833 4

NO FRACTURED FORM: 5/0

1
-----------
1
1 + -------
1
1 + ---
2

NO FRACTURED FORM: 8 / -11

NO FRACTURED FORM: 21814 / 6833

80
Name: Wordlist KLTE93 - 6

Files:
program word.pas
input word.inp
output word.out

Task:

The Mumble Puzzle Company produces word puzzles for newspapers across the country.
Your boss has decided he wants all possible words to have a number. To be sure of not
missing a word, and because you have a computer to do all the work anyway, he wants all
strings of one to twenty lower-case letters included. The words are ordered first by length,
then alphabetically. The list looks like this:

1 a
2 b

26 z
27 aa
28 ab

310012476284 a10ngword

Your job is to produce a program that will translate between the position numbers and
the words. Input to the program will be a list of numbers and words, one per line,
terminated by end-of file. Each word or number starts in the first column. A number consists
only of digi ts (O-9). A word consists only of lower-case 1etters (a-z). No word will be
longer than 20 letters. Your program must produce the line in the word list that contains
the number or word given in the input in the form of the number, at least one space,
followed by the word. Numbers that have more than three digits must be separated by commas
at thousands, millions, and so on.

Samples:

INPUT OUTPUT

psychopathological 19, 011, 949,514, 367,212,753, 99 0,730 psychopathological


1347896067682984 1,347,896,067,682,984 information
751174307943 751,174,307,943 computing
fun 4,616 fun
zzzzzzzzzzzzzzzzzzzz 20,725,274,851,017,785,518,433,805,270 zzzzzzzzzzzzzzzzzzzz

81

You might also like