programozási versenyfeladatok - programing contests

134
Programozói versenyfeladatok, alapvető matematikai algoritmusok Kiss Csaba Zsolt Programtervező matematikus KLTE Debrecen 1994.

Upload: csaba

Post on 29-Dec-2014

588 views

Category:

Documents


6 download

DESCRIPTION

Programozási Versenyfeladatok - Programming Contests

TRANSCRIPT

Page 1: Programozási Versenyfeladatok - Programing Contests

Programozói versenyfeladatok,

alapvető matematikai algoritmusok

Kiss Csaba Zsolt

Programtervező matematikus

KLTE

Debrecen

1994.

Page 2: Programozási Versenyfeladatok - Programing Contests

Tartalomjegyzék

Bevezetés 2A versenyekről. 31. Kombinatorikai algoritmusok 6

1.1. Ismétlés nélküli permutációk. 61.2. Ismétléses permutációk 101.3. Kombinációk 131.4. Egy halmaz összes részhalmazai, particionálása 161.5. Gray kódok 23

2. Geometriai algoritmusok 26Bevezetés 262.1. Szakaszok metszete 282.2. Poligon és pont 312.3. Ponthalmaz konvex burka 34

3. Gráfalgoritmusok 39Bevezetés 393.1. Mélységi keresés 403.2. Optimális keresés 44

Függelék 52Ábrák, programok listája 52Problémák listája 52

1

Page 3: Programozási Versenyfeladatok - Programing Contests

Bevezetés

A dolgozat címében hivatkozott versenyfeladatok az ACM szervezésében rendezett egyetemiprogramozó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énylegeslebonyolítását kell érteni és a feladatok kiválasztását. A helyi versenyekről tovább jutó csapatokvesznek részt a második fordulóban (egyetemenként legfeljebb egy csapat), amelyet már az ACMadott szervezete szervez. A második fordulóban (Regional Final - területi döntő) általában valamilyennagyobb területi egység (Pl. Kalifornia, Nyugat-Európa) egyetemeinek csapatai versenyeznek. Aterületi döntőkből egy-három csapat juthat tovább a döntőbe, amely mindig valamelyik USA-belinagyvá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 ésszép megoldásokat, a megoldásokhoz felhasmált alapvető matematikai algoritmusokat úgy éreztemmindenképpen szükséges rendszerezve megörökíteni, ehhez kínált kiváló fórumot a diplomadolgozatom.A dolgozat melléklete kb. 90 eredeti versenyfeladatot tartalmaz, amely biztosan nagyon hasznos leszaz egyetemünkön folyó első és másod éves programozó-matematikus, matematikus, informatika ésmatematika tanár szakos hallgatók különböző tantárgyainak gyakorlati oktatásához. . A feladatokangol nyelvűek, mert a versenyek hivatalos nyelve az angol.A dolgozatban található alapvető matematikai algoritmusok segítségével mintegy 30 (általában anehezebbek közé sorolt probléma) oldható meg. Az algoritmusok kisebb módosításaival továbbifeladatok megoldhatók. Az egyes algoritmusoknál hivatkozás található a feladatokra, amelyekmegoldásához az adott algoritmus jó hatásfokkal felhasználható. Az egyes algoritmusok újabbproblé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árainknakakik nélkül még az így elért szerény eredményeinket sem értük volna el, név szerint: Kuki Attilának ahelyi versenyek szervezéséért és az európai döntőre való kiutazás szervezéséért, valamint hasznostaná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énkmegköszönni anyagi támogatásukat azon cégeknek és szervezeteknek akik nélkül semmiképpen semké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éhezadott hasznos tanácsaikat és bölcs észrevételeiket.

2

Page 4: Programozási Versenyfeladatok - Programing Contests

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öttkezdetben lehetett egy diplomás is, később diplomások részvétele nem volt megengedett. A versenyideje általában 5 óra. A csapatok a verseny ideje alatt egy darab IBM PC típusú számítógépethasználhatnak a szükséges fordítóprogrammal felszerelve, ez a TURBO PASCAL 5.0 -ás verziójavolt. 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épekhasználata sem. A csapatoknak a verseny ideje alatt 5-8 problémát kell megoldaniuk. A problémákközött semmilyen sorrendiség sincs. A verseny nyelve angol, ezért a feladatok szövege, a zsűrinekfeltett 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élrafenntartott mágneslemezen kell a zsűrihez eljuttatniuk. A zsűri a kódot lefordít ja és saját inputadataival teszteli. A programoknak 1 perc futásidő áll rendelkezésére, ez alatt kell outputotprodukálniuk. Az output alapján a zsűri a következő válaszokat adhatja a csapatoknak:

1. Syntax Error - fordítási hiba2. Run Time Error - Futás közbeni programhiba, pl O-val való osztás3. Time Limit Exceded - Időtúllépés4. 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éntméri a verseny kezdetétől a megoldáshoz felhasznált időt. Az 1.-4. esetben (és minden továbbisikertelen kísérlet után) a zsűri az adott csapatnak adott probléma megoldásához felhasznált idejét 20perccel növeli.A verseny ideje alatt az egyes feladatokkal kapcsolatban felmerült értelmezési stb. problémákkalkapcsolatban a csapatok írásban kérdéseket tehetnek fel a zsűrinek, aki szintén írásban kötelesvá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étmennyisé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 averseny 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 BudapestiMűszaki Egyetemen (BME) rendezett versennyel, ahol nemcsak a BME csapatai, hanem a fóvárosiegyetemeken kívül vidéki csapatok is indultak. Ezen a versenyen a KL TE 3 csapatot indított, melyeka középmezőnyben végeztek. 1991 után minden évben a fóvárosban és Debrecenben is rendeztekversenyeket. Ezeken a versenyeken az induló csapatok száma nagyjából állandó volt: Budapesten kb25, míg Debrecenben kb 10.

3

Page 5: Programozási Versenyfeladatok - Programing Contests

A versenyek tapasztalatai

A következő néhány mondatban a versenyeken, a problémák megoldásával kapcsolatban szerzetttapasztalatokró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, vagyproblémás feladat esetén együtt keresik a megoldást és valósítják meg a kivitelezést. A másikmódszer, hogy minden feladat elvi megoldását a csapattagok együtt keresik, csak a konkrétmegvalósítás ideje alatt dolgoznak különböző feladatokon a csapattagok. De ezektől különböző másmódszerek is kialakulhattak, valószínűleg erre nincs általános alkalmazható stratégia. A feladatokmegoldásakor szerenesés esetben, amikor egyszerre több feladat elvi megoldása is elkészült, a szűkkeresztmetszetet a rendelkezésre álló egyetlen számítógép gépideje (5 óra) jelenti. Érdemes alegkönnyebb, legegyszerűbb probléma megoldásának megvalósításával kezdeni. A megoldásokbannem kell szépségre és az eleganci ára törekedni, mert a zsűri ezt nem értékeli. Sokkal inkább a kódegyszerű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 ismegoldható. Azoknál a feladatoknál, ahol a megoldást el lehet érni a feladatbeli objektumok összesesetének (pl. összes permutáció) vizsgálatával, ott a program rendelkezésére álló 1 perces futási időrekell 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 aszép és "eszes" megoldás megkeresésévei foglalkozni. A későbbiekben az adott helyen az egyesalgoritmusok 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, amelyXXXXéé-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 szerintnö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 akövetkezőek:

1. Szimulációs feladatokEzekben 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 feladatpontos 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 Pascalnyelvvel ismerkedőknek ajánlhatjuk. Megoldásukhoz csak alapvető matematikai ismeretekre vanszükség.

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

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

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

4

Page 6: Programozási Versenyfeladatok - Programing Contests

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 KLTE, Debrecen 1991. JúniusIOAG91 * Athen, 3rd International 1991. Május

Olympiad in InformaticsTUBP91 1 BME, Budapest 1991. OktóberRUGB91 2 Gent, Belgium 1991. NovemberACMF91 3 USA 1991.USSC92 2 ?, USA 1992.ODUN92 1 Norfolk, Va USA 1992. SzeptemberTUBP92 1 BME, Budapest 1992. OktóberKLTE92 1 KLTE Debrecen 1992. OktóberRUGB92 2 Gent, Belgium 1992. NovemberACMF92 3 Indíanapolis, USA 1992.KLTE93 1 KLTE, Debrecen 1993. Szeptember

5

Page 7: Programozási Versenyfeladatok - Programing Contests

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 pontosdefmí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! vektorttartalmaz. Vegyük észre, hogy S elemeit programmal könnyen lehet generálni: kis n esetén n-l darabegymá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 egyszerumódszert kapnánk P! generálására. A Fike módszere a következő egy-egy értelmű megfeleltetést adjaS é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 ak-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 fentleírtaknak megfelelően a kapcsolódó permutációt.Észrevehető, hogy a fenti algoritmus redundáns elemeket tartalmaz (pl ha dk = k, akkor feleslegescsere), ezen elemek kiküszöbölésére tett módosítást 1976-ban J. S. Rohl. A Rohl által módosítottalgoritmus 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 beginproe (p) ;temp: =p [nl ;for dn:=n-l downto 1 do

beginp[n) :=p[dn) r p ldn ) :=temp;p.ro c t p j rp j dn l r=p In l r

end;p[n) :=temp;

endelse begin

permute (k+l) ;t emp :=p [k) ;for dk:=k-l downto 1 do

beginp [k) :=p [dk) ;

6

Page 8: Programozási Versenyfeladatok - Programing Contests

p[dk] :=tempipermute(k+l)ip [dk] :=p [k] i

e rid rp[k] :=tempi

endiendibe gin {Fike_Rohl perm}

for i:=l to n do p[i] :=iipermute(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 aproblémákban ahol a feladat szempontjából n állandó és n nem túl nagy (n<6), elképzelhető olyaneljárás is amely n darab egymásba ágyazott ciklust tartalmaz az S elemeinek generálásához. Ennekaz 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 lexikografikussorrendben követeli meg tőlünk a permutációk felsorolását, akkor a módszerek egy újabb családjávalkell megismerkednünk [We1ll971] . Most egy olyan módszert mutatunk be, amely 1812-bőlszármazik, első említése [FiscI812] majd [ShenI962] . A módszer lényege négy lépés alkalmazásaegy 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 sorrendbengenerálja egy halmaz partícióit

Most egy másik, a permutációkat lexikografikusan felsoroló módszer mutatunk be. P! egy általánoselemének generálásakor az összes N={l,2 ..n} számnak hozzá kell rendelődnie a Pl -hez, majd azN\ {Pl} -beli összes elemnek hozzá kell rendelődnie a P2-höz, és így tovább. Ezek alapjánalgoritmusunk szerkezete a következő: Ahhoz, hogy a permutációkat lexikografikus sorrendbenkapjuk 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ő sorrendbenkapjuk.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 sokadminisztrációs lépéssei járna, ezért kihasználva a jelen probléma specifikurnát a megfelelő listát egytömbbel szimuláljuk, legyen ez a:array[O ..n} o/integer. A tömb egy elemének indexe reprezentáljai-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

Page 9: Programozási Versenyfeladatok - Programing Contests

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óktárolásához, valamint már létezik a PrintPerm eljárás a kész permutációk megjelenítéséhez. Ekkor apermutációkat lexikografikusan felsoroló algoritmus pascal kódja a következő:

procedure enum(i:integer);var t:integer;begin

t:=Oiwhile a[t)<> O dobegin

p[i]:=a[t];if i<> nthen

begina [t] :=a [a [t] ] ;enum(i+l) ;a [t] :=p [i] ;

endelse

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ényegeskülönbség nincs. Ezen azt kell érteni, hogy a megoldások a futásra felhasználható idő (1 perc) alattnagyjából n=ll-ig képesek az összes permutációt előállítani. Természetesen a fenti módszerekenkívül számos más módszer is ismeretes, melyek más-más célra használhatók a legalkalmasabban. Akü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álmegoldást. A (c)-ben megfogalmazott probléma speciális esete (n=k) annak a problémának amikoregy n elemű halmaz k-ad osztályú kombinációinak összes permutációit rendezzük lexikografikusan ésezek 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.1. S. Rohl (1976). Programming improvements to Fike's algorithm for generatingpermutations. The Computer Journal, Vol. 19, p 156.

[Rohll976]:

8

Page 10: Programozási Versenyfeladatok - Programing Contests

[WeIll 1971]:

[Fisc1912]:

[Shen1962]:[RoyI978]:[Ivesl976]:

[Brow 1970]:

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

9

Page 11: Programozási Versenyfeladatok - Programing Contests

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 fentipermutációkat: Válasszunk M-ből egy elemet az összes lehetséges módon ez lesz Pl' minden egyesilyen választás után válasszunk egy elemet M\{Pl}-ből P2-helyére, ... , és végül minden egyes Pn-lkiválasztása után Pn helyére válasszunk M \ {Pl' P2"'" Pn-l} -ből, mint az előző fejezetben. Ha r=nakkor az ismétlés nélküli permutációkat kapjuk. Ha az 'összes lehetséges módon' történő választástaz elemek növekvő sorrendjében végezzük el, akkor a permutációkat is lexikografikusan ebben asorrendben kapjuk. Rohl 1978-ban publikálta [Roh1l978] a fenti módszert némi általánosítással: Haaz algoritmus során a kiválasztásokat nem végezzük el csak Ps -ig (S < n )-ig akkor n-elem s-edosztá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;

varp:intvect;k:integer;

procedure choose(k:integer);var

i:integer;begin

for i:=l to r doif f[i] <> O thenbegin

p [k] : =m [i] ;dec(f[i]);if k<>rO then choose(k+l) else proc(p);inc(f[i]);

endend;

begin {genperm}choose(l);end;

Fig. 1.2.1.: Rohl algoritmusa (1978).

10

Page 12: Programozási Versenyfeladatok - Programing Contests

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

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

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

i :integer iresult:longinti

Beginresult:=liif k<>O then

for i:=O to (k-1) do result:=(result div (i+1) )*(n-i)inalatt 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

* )

varH,MM,J:intvectiq,i,jj:integerinn,v:longinti

beginfor i:=O to r-1 do begin h[i] :=OiMM[i] :=Oij[i] :=1 endifor i:=O to n-1 dobegin

MM[p[i]] :=MM[p[i] ]+n_alatt k(h[p[i]],j [p[i]]) iinc(h[p[i]]) iinc(j [p[i]]) ifor q:=O to p[i]-l do inc(h[q])i

e nd rv:=liNN:=Oiq:=f[r-1]ifor jj:=r-2 downto O do

beginNN:=NN+MM[jj]*Viq:=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

Page 13: Programozási Versenyfeladatok - Programing Contests

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) egyszeruenmegadható 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,

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

r' := {r -1, ha f[PI] = 1r , egyébkén!

(1)

é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

UUSC85-2

TUBP91-4RUGB92-1RUGB92-4

ACMF92-2KLTE93-3

Instrukció

Az összes esetek száma (kb. 9!) lehetővé teszi, hogy egyenként megvizsgáljuk őketA megadott öt szám összes permutációit (5!) vizsgáljuk, az összes lehetségesmüveletjelezéssel (44).Az egyenlő számjegyek elhagyása után az összes esetek száma 10!Ismétléses permutációk lexikografikusanMivel a gráf csúcsainak száma nem több mint 8, ezért a csúcsok összes lehetségessorrendjét megvizsgálva (8!) a minimálisat bizonyosan megtaláljukA hálózatba kapcsolt gépek maximális száma 8, ezért az összes eset vizsgálatalehetséges.

Irodalomjegyzék az 1.2 fejezethez

[Rohll978]:

[we1ll971 ]:

[Bratl967]:[Sag1964]:

J. S. Rohl. (1978). Generating permutations by choosing. The Computer Journal,Vol 21., p 303.M. B. Wells (1971). Elements ofCombinatorial Computing. Pergamon Press, NewYorkP. Bratley (1967).Permutations with repetitions. CACM Vol. 10. p. 450T. W. Sag (1964) Permutations of set with repetitions. CACM Vol. 7. p 585.

12

Page 14: Programozási Versenyfeladatok - Programing Contests

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ókkalfoglalkozó 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 foglalkozunka "rendezettlen" kombinációk generálásával. A lexikografikus algoritmusok közül is csak azzalfoglalkozunk, 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,···, Crvektor,aholCi E {O, 1, .... ,n-i} és

r-i

Ci = Pi - i +Lo i, j

j=lahol

{O,hap.<p.o = 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énekmeghatározásához az így nyert listában meg kell számlálnunk a P2 -t megelőző elemek számát, majdP2 -t is töröljük a listából a többi Ci -t ugyanilyen módszerrel kapjuk:

proeedure eodingivar i,t, eount:integeribeginiInit;for i:=l to r dobegin

eount:=O;t:=O;while p[i)<>a[t) dobegin

t:=a[t);ine(eount)

end;eli] :=eountia [t) :=a [a [t) )

end;

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

13

Page 15: Programozási Versenyfeladatok - Programing Contests

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 rbegin

t:=O;for j :=1 to c[i] do t:=a[t];p [i] :=a [t] ;a [t] :=a [a [t] ] ;

endend;

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 kisebbinverzió 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örrPermGen inverzét, vagyis azt a RankrPerm nevű eljárást amely lexikografikus sorrendbenmegsorszá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, ... , cj -vel kezdődő Cn. r = CI' Cz, ... , Ci>"" Cr

inverziót pontosan [Pm-i, r-i)1 olyan inverzió előz meg, amelyeknek c\ ,cI

Z , •.• ,clj előtagjára az igaz,

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

értékeit, Cj+Z pedig [O,1,..,n-(i+2)] intervallum on fut végig, és így tovább. Ekkor az így összeszámoltesetek 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 egyadott 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ódszeralkalmazásával jutunk. A módszert most is az inverzfüggvényre (a RankrPerm eljárás) alkalmazzuk:

14

Page 16: Programozási Versenyfeladatok - Programing Contests

procedure rPermGen(rank, k:integer; var c:codeword);var i:integer;be gin

for i:=n-k downto O doif 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;

endend;

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. Azeredeti problémához kapcsolódó feladatokat találunk még [Welll971] -ben.

Kapcsolódó versenyfeladatok:

FeladatKLTE91-3KLTE92-1

Instrukció

Lexikografikus kombinációk felsorolása

Irodalomjegyzék az 1.3 fejezethez

[We1ll971]:

G. D. Knott (1976). A Numbering System for Permutations ofCombinations.Communications of ACM, Vol 19, p 355.M. B. Wells (1971). Elements of combinatarial programming. p 130.

[Knot197 6]:

15

Page 17: Programozási Versenyfeladatok - Programing Contests

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) összesré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 eza 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 akö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 pontosanakkor 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 sorrendetadja, mint az őket reprezentáló bináris számokon (bit-sztringeken) értelmezett lexikografikusrendezés.

Ha valamely feladat a részhalmazok felsorolásán kívül, nem követeli meg tőlünk a lexikografikusrendezettséget, akkor az {1,2, ... ,n} halmaz részhalmazainak felsorolása binárisreprezentá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 aszá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, eztvaló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észhalmazfelsorolása kb 40 másodpercet vesz igenybe

vart: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) :longintivar c:longint;i:integer;be gin c:=l; for i:=l to x do c:=c*2; Kettoad:=c end;

16

Page 18: Programozási Versenyfeladatok - Programing Contests

procedure subset(t:integerivar r:integer)ivar

k:integerih:longintibegin

for i:=l to n do b[i] :=Oir:=Oik:=lirepeat

h:=kettoad(n-k)iif t<= h then begin b[k] :=li inc(r)i arr] :=k endit:=t-(l-b[k])*h-b[k]iinc (k)

until ((k>n) or (t=O))endi

beginfor t:=l to kettoad(n) dobegin

subset(t,r)iwritelniwrite(t,' :')ifor i:=l to r do write(a[i],' 'li

endend.

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, bglobális változóban t-edik részhalmazt, az r-paraméterében pedig a t.-részhalmaz elemszámát adjavissza.

Legyen Z; = {I, 2, .... , n}. Ekkor a Z; halmaz egy partíciója az azon halmazokP = {7rl' 7r2, ••• , 7rm} halmaza, amelyre

7ri n 7rj = 0, ha i'1':. jés 7r

1'1':.0, i=I,2, ... ,m

(2 )m

és Unt = Z;i=l

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= 1Tegyü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_l U {a} összes partícióit !Világos, hogy azon partíció száma, amelyekben {a} szerepel Bn-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

Page 19: Programozási Versenyfeladatok - Programing Contests

( 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_iVagyis H; = Hn-1 u {a} összes partícióinak száma:

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

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

Fig. 1.4.2.: s; értékei

124213597

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ó111111121121112211231211121212131221122212231231123212331234

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; nemkerülhet 1ttbe, ha j > i. A következőkben azt vizsgáljuk, hogy a Z; halmaz összes partícióinakkódszavai hogyan vezethetők le a Zn_l halmaz összes partícióit leíró kódszavak sorozatábólhozzá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 azaktuá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 akövetkező:

18

Page 20: Programozási Versenyfeladatok - Programing Contests

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

procedure SetPartitions(n:integer)ivar c:codewordiprocedure SP(m,p:integer)jvar i:integeri

beginif p > n then PrintPartition(c)else

beginfor i:=l to m dobegin

c[p] :=iiSP(m, p+1) iendic[p] :=m+1i SP(m+1, p+1)

endendi

beginSP(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 sec11 < 4 sec12 < 21 sec13 < 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 hafeldatbeli n < 13.Ha az eredeti problémát, úgy módosít juk, hogy csupán a lexikografikus sorrendben t. partíciótkeressük, akkor a fenti Er-féle algoritmus nem használható hatékonyan, hiszen ahhoz, hogymegkapjuk 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 atermé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(cl,c2, •. ,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

Page 21: Programozási Versenyfeladatok - Programing Contests

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) = higaz 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ámaDn (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)ivar r:integer;begin

t:=l; d:=l;for r:=2 to n

begindo t:=t+([r]-1)*Dn[r+1, d];if c[r]> d then d:=c[r]

endend;

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.2fejezetben a következő algoritmust kapjuk:

program Set_Partitionsiconst

Bell:array [0 ..15] of longint=(1, 1, 2, 5, 15,

52, 203, 877, 4140, 21147,115975, 678570, 4213597, 27644437, 190899322,1382958545 )i

varn:integerit:longint;r,i,j:byteiDn:array[1 ..18,1 ..18] of longintiC: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+1ifor 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

Page 22: Programozási Versenyfeladatok - Programing Contests

endi

Procedure partition(tO:longint var d:byte)ivar r:integeri

t,m,k:longintiBegin

t:=tO id: =1 ifor r:=2 to n do

beginm r=O)repeat inc(m) until t <= m * Dn[r+1,d])iif d+1 < m then m:=d+1ic [r] : =mrt:=t-(m-1)*Dn[r+1,d]iif d < m then d:=mi

endiendi

beginwritelni write(' n:')i readln(n)iPreCalcD(n)i c[l] :=lifor 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

beginwrite(j,'. reszhalmaz elemei:')ifor i:=l to n do if c[i]=j then write(i, " ')iwriteln

e nd rend

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 amá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óprogramvé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-7A probléma neve: SzállításMivel a probléma csupán az n<100 korlátozást tartalmazza, ezért az összes eset generálása ésellenőrzése a fenti módszerek bármelyikévei is, nem valószínű, hogy megoldáshoz vezet akkor ha azsúri teszt inputadataiban a csomagok száma több, mint 13. Az előző korlátozás bevezetésévei 4.4algoritmusunkkal a csomagok halmazának összes partícióinak előállításával és ellenőrzéséveikivá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

Page 23: Programozási Versenyfeladatok - Programing Contests

Irodalomjegyzék az 1.4 fejezethez

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

22

Page 24: Programozási Versenyfeladatok - Programing Contests

1.5. Gray kódok

A Gray kódok olyan k-bites bitminták sorozata, amelyek olyan tulajdonságúak, hogy az egymástkövetőek egymástól egyetlen bitben különböznek. Például a következő 3-bites Gray kódokalkalmasak 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 O100 1 4101 2 5001 3 1011 4 3010 5 2110 6 6111 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 azis igaz, hogy az utolsó és az első is egyetlen bitben különbözik egymástól. A fentiek nem CiklikusGray kódok. A továbbiakban csak Ciklikus Gray kódokkal foglalkozunk, ezért a rövidség miatt csakGray kódokként hivatkozunk rájuk.

Gray kódok Sorszám Decimálisérték

000 O O001 1 1011 2 3010 3 2110 4 6111 5 7101 6 5100 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állyalgenerálhatóak: Minden egyes lépésben az adott Gray kódból egyetlen bit negálásával apjuk akövetkező Gray kódot. Meg kell határoznunk ennek a bitnek a pozícióját. Erre a pozícióra pedig azigaz, hogy pontosan fele annyiszor kel1 változtatni, mint a tőle közvetlenül jobbra ál1ót. Ez a módszerviszonylag könnyen programozható, de megvan az a hátránya, hogyan-edik Gray kódot csak amegelő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 kellmegoldanunk 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űbbmegoldást a (b)-problémához!Jelöljük G(k) = (go. gp ...• g2k_) -val a k bites Gray kódokat.

23

Page 25: Programozási Versenyfeladatok - Programing Contests

Ekkor G-t adefmiálhatjuk:

{G(1) = (0,1)

G(n + 1) = (Ogo,Ogpo .. ,Og2n_l' Ig2n_, , ... , Igo)

következő rekurzióval

(1)

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

(mmOd2" )

g(m, n) = 2n-'

< 1

Vagyis a (b) problémát akár egy, a (2) formulát használó algoritmussal is megoldhat juk,

( 2)

LegyenD(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+ 1,D,ev(n)), ahol D,ev(n):= D(n) jordítottja(3)

Ha

ésn

g; = (bn,bn_p ••• ,'1), hogy i = 'Llj2jj=O

(4)

akkor

b. =/. xor l, IJ J J-

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.Azezen 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 azta 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árisl-bittel jobbratolást fed, akkor a programunk a szám bináris alakjából egyetlen utasítássalelőállíthatja a megfelelő Gray kódot bitmintáját. Mivel a feladatok között találtam olyat, amelymegoldásához az (a) ill. (b) problémát is meg kell oldani, ezért a Gray kód generáló algoritmusunkatebbe ágyazva közöljük:

USEC92-1A 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 programinputjai. A program outputja a megfelelő Gray kódok decimális alakja:A problémát kétré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 fentemIített pascalbeli Word típu st, valamint a memóriában elfér az összes l5-bites Gray-kód, amely

24

Page 26: Programozási Versenyfeladatok - Programing Contests

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 akövetelményeknekmegfelelő 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;

beginelrserigetmem(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 falseend.

Fig. 1.5.3.: Twiddler.pas

25

Page 27: Programozási Versenyfeladatok - Programing Contests

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, atérinformatikai, térképészeti vagy háromdimenziós szimulációs problémák. A geometriaialgoritmusok szintén nagyon fontosak az olyan komplex fizikai rendszerek tervezésében és aelemzésében, mint például az épületek, autók, gépek és integráltáramkörök. Az ilyenprogramrendszerekben a tervezők a fizikai objektumoknak megfeleitetett gépi objektumokkaldolgoznak. Ezen gépi objektumok megfelelő szintű számítógépes kezelése, megjelenítése igazánkomoly feladat.Az ilyen alkalmazások olyan alapvető objektumai, mint a pontok, szakaszok vagy poligonok és ahozzájuk kapcsolódó alapvető eljárások adják az általában a nehezebbek közé sorolható geometriaiversenyfeladatok 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áskeresé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épesprogramot.Néhány geometriai versenyfeladat megoldásához elegendő a középiskolai koordinátageometriábóltanult 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ákmegoldásához hasonlít.További "geometriai" problémák megoldását tisztán vagy nagyrészt kombinatorikai algoritmusokadjá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, amelyekmegoldásához az első csoportbeli alapvető geometriai függvények pontos megvalósítása, valamintkombinatorikai alapismeretek szükségesek.A legtöbb algoritmus, amit tanulmányozni fogunk a legegyszerűbb geometriai objektumokkal fogdolgozni a két dimenziós véges, de megfelelően kiterjedt síkon. A legalapvetőbb geometriaiobjektumot a pontot egy számpárral fogjuk jellemezni (a pont 'koordinátái' a derékszögú koordinátarendszerben). A szakasz reprezentációja egy pontpár, amelyeket az adott szakasz összeköt. A poligonesetünkben pontok listája, és feltételezzük, hogy az egymásután következő pontok szakaszokkalvannak összekötve, valamint, hogy az utolsó pontot az elsővel szintén egy szakasz köti össze, ígyalkotva 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 azobjektumokat 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 egyhalmazát érinti, akkor a reprezentációban szintén az array[O ..max] of pont definíciót fogjukalkalmazni, ahol max valamilyen elegendően nagy szám.

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

type pont = recordx :integeriy: integer

endi

type szakasz = recordpl:pontip2:pont

26

Page 28: Programozási Versenyfeladatok - Programing Contests

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ósreprezentáció ugyanígy használható lenne, de az egész értékeket használata sokkal átláthatóbb éshatékonyabb (az egész számok műveleteit a számítógép sokkal gyorsabban végzi, mint alebegőpontosakat) programot eredményez, nem beszélve arról, hogy a versenyfeladatok általábanmegelégszenekaz egész értékű geometriai programozással is.

27

Page 29: Programozási Versenyfeladatok - Programing Contests

2.1. Szakaszok metszete

Az első probléma melyet tárgyalni fogunk az egyik legalapvetőbb probléma ezért számos másalgoritmus 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ő, hogymetszik-e egymást vagy sem. A következő ábra néhány lehetséges előfordulást mutat:

f·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 szakaszainktartalmazzák-e ezt a metszéspontot. Amennyiben a kérdéses egyenesek párhuzamosak, akkor azt kellvizsgálnunk, hogy valamely szakasz végpontja a másik szakaszra esik-e. Az egyenesekmetszé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) :booleanjvar

nev,a,b,c,d,x,y:realiflagl,flag2,flag3,flag4:booleanj

begina:=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}

thenif 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))/nevix:=(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

endelse {a szakaszok parhuzamosak}

28

Page 30: Programozási Versenyfeladatok - Programing Contests

if a*p2.x+b*p2.y=a*pO.x+b*pO.ythen 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;endelse

metszet:=falseelse {valamelyik szakasz pont l}

if ((abs(a)+abs(b))>O) and (abs(c)+abs(d)=O){a masodik szakasz pont}

thenif a*p2.x+b*p2.y=a*pO.x+b*pO.ythen

metszet:=((pO.x<=p2.x) and (p2.x<=pl.x)) or((pl.x<=p2.x) and (p2.x<=pO.x))

elsemetszet:=false

elseif (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.ythen 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. Aversenyfeladatok 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ényegesenegyszerűbb). A fuggvény alkalmazhatóságát megnehezíti, hogy a kód nem eléggé átlátható és ezzelegyütt nehezen debug-olható,Az algoritmust megvalósító fuggvényt könnyedén át lehet alakítani úgy, hogy amennyiben vanmetszéspont annak koordinátáit adja is vissza, hiszen pl. nem elfajuló esetben a fuggvény x,yvá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ó egyenesekmetszé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 algoritmusnakmegvan az az előnye a fentivel szemben, hogy a (helyes) pascal kódja talán kevesebb sorból állna.

29

Page 31: Programozási Versenyfeladatok - Programing Contests

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

Page 32: Programozási Versenyfeladatok - Programing Contests

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 vagyoldalá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 apoligont véges sok pont feszíti ki, ezért valamely irányban egy elegendően távoli pontbiztosan 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 igenkeressü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 ezpá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 egyadott 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 acsúcsok száma) fog végrehajtódni, véges sok lépésben megtaláljuk a megfelelő Q pontot.

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

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:

Q

31

Page 33: Programozási Versenyfeladatok - Programing Contests

program insideiuses crticonst max=20i

type pont=record x,y:integer endi

var poligon: array[O ..max] of pontip,q:ponticount,i,n:integerictrl, ctr12:booleani

procedure InputPoligonivar i:integeribegin

clrscriwrite('n :')ireadln(n)iwriteln('-------------------------------------------')ifor i:=l to n dobegin

writeln('Az " i , '-edik csucs koordinatai')iwrite('x: ')ireadln(poligon[i] .X)iwrite('y: ')ireadln(poligon[i] .y)i

endipoligon[O] :=poligon[n]i

endi

procedure InputPontibegin

writeln('A pont koordinatai')iwrite('x: ')ireadln(p.x)i write('y: ')ireadln(p.y)i

endi

beginInputPoligoniInputPonti

ctr12:=falsei i:=Oirepeat

ctr12:=ctr12 or metszet2(p,p,poligon[i],poligon[i+l])i.inc t í.j r

until (ctr12) or (i=n-l)iif ctr12 then writeln('*8enne')else be gin

q.x:=-maxintifor i:=l to n dobegin

if poligon[i] .x > q.xthen

begin q.x:=poligon[i] .x+li q.y:=poligon[i].y endiendi

repeatq.y:=q.y+lictrl:=falseifor i:=l to n do ctrl:=ctrl or

metszet(poligon[i],poligon[i],p,q)iuntil not ctrli

32

Page 34: Programozási Versenyfeladatok - Programing Contests

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 ');

endend;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 amegadott sorrendben egy zárt, önmagát nem metsző alakzat valamilyen rögzített körbejárás szerinticsúcsai. Az alábbi poligonokat algoritmusunk inputjaként meg lehet úgy adni, hogy kielégítsék efelté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, apoligonon garantáltan kívülre eső ponton át, ám bármilyen legyen is ez (mindegy, hogy a poligoncsúcsain megy át vagy a poligon valamely oldalát tartalmazza ), ennek a félegyenesnek és apoligonnak számolja össze a metszéspontjait, úgy, hogy közben figyeli az előforduló speciáliseseteket, 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ébenvan-elP2.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

FeladatRUGB92-3

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

IOAG91-2

33

Page 35: Programozási Versenyfeladatok - Programing Contests

2.3. Ponthalmaz konvex burka

Ebben a fejezetben egy olyan algoritmust kell készítenünk, amely meghatározza egy adottponthalmaz konvex burkát. A konvex burok nem más, mint egy konvex poligon, melynek csúcsai azadott 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öbbpontja egy egyenesbe esik a ponthalmaz határán. Ilyenkor algoritmusunk outputját csak a poligoncsúcsaira eső pontok 'alkotják. Azaz a 2.3.1 b) ábrán látható ponthalmaz konvex burkát azABCDEFGH-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átatengelyekkel 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énythaszná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értaz algoritmus a bemenetként kapott tömb elemeit egyszeruen átrendezi, úgy, hogy az első Mtö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 ponthalmazkonvex burkát alkotó pontokat, még nem oldottuk meg teljesen a problémát. Az így megjelöltpontokat ugyanis úgy kell sorrendbe rendeznünk, hogy azok valóban poligont alkossanak. Azaz a2.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 ponthelyvektorának valamely rögzített egyenessei vett szöge), majd a pontokat a hozzájuk tartozó r értékalapján rendezzük akkor a kívánt sorrendet kapjuk. Megfontolandó az, hogy az egész probléma nemvezethető-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 egykódrésze, amely a fent leírtak szerinti legkisebb r értékü pontot választja ki, anélkül, hogytrigonometrikus fuggvényeket használna. A trigonometrikus fuggvények kiküszöbölése azalgoritmusbó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 xkoordiná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árnincsenek pontok), majd ezt az egyenest forgassuk az előző pont körül az óramutató

34

Page 36: Programozási Versenyfeladatok - Programing Contests

járásával ellentétes irányban addig, amíg valamely pontba ütközünk. Ha egyszerre többpontba ü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éntmegjelölt pont körül forgatjuk az eddigiekkel megegyező irányban addig amíg valamelypontba nem ütközünk. Ha egyszerre több pontot is elért az egyenesünk, akkor mindig atá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 pontokataz input tömb elejére cseréli és a már beválasztott pontokat nem vizsgálja újra. A következő ábra azalgoritmus működését szemlélteti:

1 1

33

4

1

3

1

4

5

1

Visszatérve a konvex burok értelmezésére, megadására, az algoritmust és így a programot isegyszeruen át lehet alakítani, úgy, hogy az a burok csúcsoktói különböző pontjait is előállítsa

4

5 3

1

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

35

Page 37: Programozási Versenyfeladatok - Programing Contests

outputként. Egyszerűen akkor, amikor egyenesünk több ponttal ütközik egyszerre, akkor az érintettpontok 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 becsomagoliconst

max=100itype

pont=recordx:integeriy:integer

erid rvar

inp,out:textiok,s:stringin,i,j,k:integeripoligon = array[O ..max] of ponti

procedure str_to_pont(s:stringivar q:pont)ivar v,j,xl,x2:integeri

sl:stringibegin

v:=pos(',',s)i sl:=copy(s,l,v-l)idelete(s,l,v)i val(sl,xl,j)ival(s,x2,j)jq.x:=xli q.y:=x2i

e nd r

function theta(pl,p2:pont) :realivar

dx,dy,ax,ay:integerit:reali

be gindx:=p2.x-pl.xiax:=abs(dx)idy:=p2.y-pl·Yiay:=abs(dY)iif (dx=O) and (dy=O) then t:=-l else t:=dy/(ax+aY)iif dx<O then t:=2-t else if dy<O then t:=4+t;theta:=t*90.00

endi

function d(pl,p2:pont) :realivar

dx,dy:realibegin

dx:=p2.x-pl.Xidy:=p2.y-pl·Yid:=sqrt(dx*dx+dy*dy)

endi

function csomag (c:integer) :integerivar

i,min,m:integeriminszog,v,mintav,th:realit:ponti

beginmin:=li

36

Page 38: Programozási Versenyfeladatok - Programing Contests

for i:=2 to n doif poligon[i] .y<poligon[min].y then min:=ielse

if poligon[i] .y=poligon [min] .ythen

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

beginth:=theta(poligon[m],poligon[i])iif th >= v then

if th < minszog thenbegin

min:=iiminszog:=th;mintav:=d(poligon[m],poligon[min])

endelse

if th minszogthen

if c*d(poligon[m],poligon[i]) > c*mintavthen

beginmin:=i; minszog:=thimintav:=d(poligon[m),poligon[min))

endend

until min=n+l;csomag:=m

end;begin

assign(inp, 'pontok.inp');assign(out, 'burok.out');reset(inp); rewrite(out);repeatreadln(inp,s);

n:=O;while s<>'*' do

begininc (n);str_to_pont(s,poligon[n))ireadln(inp,s)

end;for i:=l to csomag(-l) do

writeln(out,poligon[i) .x,',' ,poligon[i) .y) iwriteln (out, '*')

until eof(inp)iclose(inp);close(out);end.

37

Page 39: Programozási Versenyfeladatok - Programing Contests

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 akö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 sorbanpontosan 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 oldalairaesnek

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 afenti 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 ponthalmazkonvex burkát. Az input pontokat egymás után egyesével adjuk meg az eljárásunknak és az eddigmegadott pontok konvex burkát adja meg lépésenként, módosítva azt minden újabb pont után haszükséges. lásd [SHAM1977]

Kapcsolódó versenyfeladatok:

FeladatIOAG91-2

ACMF92-4KLTE93-2

InstrukcióA feladat megoldása mindkét eddig ismertetett algoritmus alkalmazásátmegköveteliA konvex burok algoritmus explicit alkalmazása.

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

Page 40: Programozási Versenyfeladatok - Programing Contests

3. Gráfalgoritmusok

Bevezetés

A programozói versenyek "nehezebb" feladatainak legnagyobb hányadát a gráfelméleti feladatokteszik 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ösbebújtatottak.A gráf, mint matematikai objektum nem más, mint csúcsok és élek véges halmaza. A csúcsok alegkülönfélébb más objektumok lehetnek, egyetlen kikötésünk, hogy valamilyen megkülönböztetésüklétezzen: legyen nevük vagy más azonosítójuk. A gráf egy éle összeköttetést, kapcsolatot reprezentála 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ő vagyhárom gráfot. Tekinthetjük például ABCDFG-t egy gráfnak. Ezt a gráfot definiálhat juk úgy, hogyfelsoroljuk 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 egyolyan 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 avégpont megegyezik (vagyis a listában egyetlen ismétlődés van). Azt a gráfot, amelyben egyetlen körsincs és összefüggő fá-nak nevezzük (a nem összefüggő, körmentes gráf ot erdő-nek nevezzük). Agrá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 élthozzá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 rendelkeziksű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övidebbidejű megvalósíthatóságot kell érteni, ennek egyik leglényegesebb komponense a kód rövidsége ésegyszerűsége) nagyban függ attól, hogy a gráfok milyen reprezentációját választottuk. Általában alegegyszerűbb kódot azon algoritmusok eredményezik, amelyekben a gráf reprezentációjakéntvalamilyen mátrixos (szomszédsági vagy összefüggőségi) megoldást választottunk. Persze vannakproblémák, amelyeknél a listás reprezentáció elkerülése sokkal "költségesebb" lenne, mint annakmegvaló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

Page 41: Programozási Versenyfeladatok - Programing Contests

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ésekrekell 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 azta 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, akkorkereső eljárásunk már véget is ért hiszen a keresett listának egyetlen elemből áll: a STARTcsúcsból.

2. Ha nem vagyunk ilyen "szerencsések", akkor keressük meg a START csúcs összesszomszédját, ezt a folyamatot kiterjesztésnek nevezzük. Az így nyert csúcsokat a STARTcsúcs "gyermekeinek", "utódjainak" vagy "rákövetkezőinek" nevezzük. Ennek a lépésnek azeredmé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úcsokatmilyen sorrendben terjesztjük ki. A két legismertebb kereső stratégia a szélességi és a mélységikeresés. A mélységi keresés alkalmával mindig olyan "messze" haladunk a gráfban a STARTcsúcstól, amilyen messze csak lehet, vagyis a fenti ábrán mélységi stratégia szerint az S II csúcskövetkezne kiterjesztésre, szélességi stratégia szerint pedig az S2. De mindennél többet mond talán azalgoritmus formális leírása.

INPUT: A gráf két csúcsa START és GOALFELADAT: Meghatározni, hogy létezik-e egyszerű út START és GOAL között.OUTPUT: Igen vagy Nem1. Legyen NYILTAK egy lista, első eleme legyen START

Legyen ZÁRT szintén egy üres lista2. Ha NYILTAK üres, akkor algoritmus vége és a válasz Nem3. 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 aZÁRT listábanb2. 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

Page 42: Programozási Versenyfeladatok - Programing Contests

A fenti algoritmus, nem használja ki az élek reflexivitását, vagyis irányított gráf okra is tökéletesenműködik. A mélységi keresési stratégiát természetesen nem csak arra használhatjuk, hogymegkeressük két csúcs között egy gráfbeli utat. Használhatjuk pl. arra is, hogy megtudjuk, hogy egyadott gráf tartalmaz-e kört. Ugyanis ha a 3bl-ben ténylegesen ki kell vennünk valamely csúcsot aZÁ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álogathatjukegy gráf összefiiggő komponenseit: Meg kell jelölnünk a kiterjesztett csúcsokat és ha a NYILTAKlistá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 nemjelö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{

input1.2.2+1.

formatum (a graf megadasa)sor csucsok szama (v)sor elek szama (e)sor elso ,1: a ket csucs sorszama amelyeket osszekot

[space]-szel elvalasztva.sor masodik,l2+2.

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;

beginv:=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;

beginassign(inp, 'deptlst.inp'); reset(inp); readln(inp,v);

41

Page 43: Programozási Versenyfeladatok - Programing Contests

readln(inp,e); for i:=l to v do graph[i] :=NIL;for j:=l to e do

beginreadln(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

beginif order[tA.v]=O then visit(tA.v) else cycle:=true;t:=tA.next

endend;

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;

beginassign(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 dobegin last:=idi

if order[k]=Othen 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 ')iwriteln;

endend;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. Aprogram 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

Page 44: Programozási Versenyfeladatok - Programing Contests

- 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 listaelemei az adott csúcs szomszédjai. Vagyis a fenti gráfot programunkban a következő tömbreprezentálja:

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

6 -> 43 -> 4 -> 62 -> 42 -> 38 -> 91 -> 2

5 -> 95 -> 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ítottgrá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áfazon összefuggő komponensének mélységi bejárását, amely a paraméterként megadott csúcsottartalmazza 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úcsravégrehajtva az eljárás megkeresi az l-es csúcs szomszédjai közül, azt amely még nem volt megjelölveaz 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 ilyetakkor ez azt jelenti, hogy, az adott csúcs minden szomszédját bejártuk, vagyis vissza kell lépnünk egyszinttel "feljebb" (backtrack) ....Egy gráf összefüggő komponenseinek leválogatására alkalmas Warshall algoritmusa is [NIE21977]

Kapcsolódó versenyfeladatok

FeladatKLTE91-5

IOAG91-4

ACMF91-1KLTE92-3KLTE92-5USEC92-3TUBP92-5ACMF92-5

InstrukcióMegoldható más, nem gráf elméleti módszerrel is. A gráf os módszer megvalósításahosszabb és bonyolultabb módszert követel.A feladatban egy gráf legtöbb csúcsot tartalmazó összefuggő komponensét kellmegkeresnünk, ez a fenti program segítségével lehetséges. Mivel a feladatban agráf a szomszédsági mátrixával adott, ezért Warshall algoritmusa is nagyon jólalkalmazható.Útkeresés.KörkeresésÚtkeresés.Útkeresés.Összefuggő komponensek szétválasztása.Vegyünk sorra minden élt a feladat irányított gráfjában. Majd az adott élt hagyjukel az eredeti gráfból . Ha ebben a gráfban létezik út az adott él végpontjai közöttakkor 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ásainakSzámítógépes Módszerei. 77 - 78 oldal.

43

Page 45: Programozási Versenyfeladatok - Programing Contests

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étejellemzi, hanem az esetleges él költsége is. Az előző fejezetbeli algoritmussal szembeni kérdéseinkpedig ú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 GOALFELADAT: Minimális költségű út keresése START és GOAL közöttOUTPUT: 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 aZÁ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. AzUTÓ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égmező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 adatokattartalmazza

minden varoshoz sorok tartoznak ,melyek a kovetezoket tartalmazzak:nev<szomszed varos neve><ut hossza>end

CONSTInputtile = 'terkep.dat';Outputtile = 'result.txt';Vegtelen = Maxint;

TYPESzam INTEGER;Szam2 REAL;

44

Page 46: Programozási Versenyfeladatok - Programing Contests

VarosNevVarosMut

string[80];AVarosListaElem;

VarosListaElem = RECORDnev 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;

BEGINi:=-2; mut:=Varosok;WHILE (mutA.nev <> a.nev) AND (mut<>NIL) DO mut .- mutA.kov;IF mut <> NIL THEN

BEGINsz:=mutA.szomszedok;WHILE (szA.nev <> b.nev) AND ( sz <> NIL) DO sz:=szA.kov;IF sz <> NIL THEN tavolsag := SZA.utELSE BEGIN writeln(out, 'tavolsag-----> error'); tavolsag .- Vegtelen; END

ENDELSE BEGIN writeln(hiba); exit end;

UtKoltseg:=tavolsag;END;

FUNCTION MutVaros (varosVAR

VarosNev) Mutato;

atmBEGIN

atm:=Varosok;

atag Mutato;

WHILE (atmA.nev <> varos) and (atmA.kov <> NIL) DOatm := atmA.kov;NEW(atag);atagA := atmA; atagA.kov

END;NIL; MutVaros := atag

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

atm:Tag;mut:Mutato;

45

Page 47: Programozási Versenyfeladatok - Programing Contests

BEGINmut := MutVaros(n); atm := mutA;IF NyiltAktElem = NIL THEN

BEGINNEW( mut );mutA := atm; mutA.koltseg :=UtKoltseg(os, atm) + os.koltseg;mutA.kov .- NyiltAktElem;{=nil}; NyiltAktElem := mut;NyiltAktElemA.szulo .- os.nev;

ENDELSE

BEGINIF os.koltseg + UtKoltseg( atm, os) > NyiltAktElemA.koltsegTHEN Illesztvaros(n, os, NyiltAktElemA.kov)ELSEBEGIN

NEW ( mut ); mutA := atm; mutA.kov .- NyiltAktElem;mutA.szulo := os.nev; mutA.koltseg .- oS.koltseg+UtKoltseg(atm, os);NyiltAktElem := mut;

ENDEND

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

BEGINWRITELN(out, 'Csucs.nev: ' atmA.nev,', koltseg:

'; ose:',atmA.szulo);atm := atmA.kov

atmA.koltseg:5:0,

END;writeln(out,' ');

end;

PROCEDURE Kiterjeszt;VAR

AktSzomszedatmose

VarosMut;Mutato;Tag;

BEGINAktSzomszed:=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

BEGINIF not Zartban_Van(AktSzomszedA.nev) THEN IllesztVaros (AktSzomszedA.nev, ose,

Nyiltak) ;AktSzomszed .- AktSzomszedA.kov

ENDEND;

46

Page 48: Programozási Versenyfeladatok - Programing Contests

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;

BEGINVarosok := NIL;ASSIGN(inp,InputFile); RESET(inp);WHILE NOT EOF(inp) DO

BEGINNEW(mut); READLN( inp, mut~.nev);mut~.koltseg := O; mut~.szulo:='KACOR'; mut~.szomszedok := NIL;READLN( inp, sor);WHILE sor<>'end' DO

BEGINNEW(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

Page 49: Programozási Versenyfeladatok - Programing Contests

new(result) ;result~:=nyiltak~; result~.kov:=NIL;min:=maxint; minmut:=NIL; os:=result~.szulo;REPEAT

ez:=zartak;WHILE (ez<>NIL) DO

BEGINIF (ez~.nev=os) AND (ez~.koltseg < min)

THEN BEGIN min:=ez~.koltseg; minmut:=ez END;ez:=ez~.kov

END;IF minmut<>NIL THENBEGIN

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 DOBEGIN

ClrScr;kit:=O;WRITE ('Nyomkovetes (i/n) ,);READLN ( Nyom );IF UpCase(nyom)='I' THEN begin Debug:=TRUE; assign(out, "); endELSE 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<>NILTHEN BEGIN

eredmuta:=Eredmeny;writeln('KESZEN VAGYUNK');writeln(out, 'A KITERJESZTESEK SZAMAatm := eredmuta;WHILE atm <> Nil DO

',kit) ;

BEGIN writeln(out,atmA.nev,',END

ELSE writeln(out, 'Nincs ut');

atm~.koltseg:5:2); atm .- atmA.kov END;

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

Page 50: Programozási Versenyfeladatok - Programing Contests

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

A program a következő outputot generálta:

Nyomkovetesstart: acel: i

(i/n): n

OUTPUT

A Nyilt Lista Lista a O. kiterjesztes utanCsucs.nev: a, koltseg: O; ose:START-CSUCS

A Zart Lista Lista a O. kiterjesztes utan

A Nyilt Lista Lista a 1. kiterjesztes utanCsucs.nev: b, koltseg: 8; ose:aCsucs.nev: e, koltseg: 9; ose:a

A Zart Lista Lista a 1.Csucs.nev: a, koltseg:CSUCS

A Nyilt Lista Lista a 1.Csucs.nev: b, koltseg:Csucs.nev: e, koltseg:

kiterjesztes utanO; ose:START-

kiterjesztes utan8; ose:a9; ose:a

A Zart Lista Lista a 1. kiterjesztes utanCsucs.nev: a, koltseg: O; ose:START-CSUCS

A Nyilt ListaCsucs.nev: e,Csucs.nev: c,Csucs.nev: e,

Lista a 2.koltseg:koltseg:koltseg:

A Zart Lista Lista a 2.Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: e,Csucs.nev: c,Csucs.nev: e,

Lista a 2.koltseg:koltseg:koltseg:

A Zart Lista Lista a 2.Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: c,Csucs.nev: d,Csucs.nev: f,

Lista a 3.koltseg:koltseg:koltseg:

kiterjesztes utan9; ose:a

14; ose:b16; ose:b

kiterjesztes utan8; ose:aO; ose:START-

kiterjesztes9; ose:a

14; ose:b16; ose:b

utan

Csucs.nev: e,Csucs.nev: c,

koltseg:koltseg:

16; ose:b18; ose:e

kiterjesztes utan8; ose:aO; ose:START-

kiterjesztes utan14; ose:b16; ose:e16; ose:e

A Zart Lista Lista a 3.Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

kiterjesztes utan9; ose:a8; ose:aO; ose:START-

A Nyilt Lista Lista a 3. kiterjesztes utanCsucs.nev: c, koltseg: 14; ose:bCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: c, koltseg: 18; ose:e

A Zart Lista Lista a 3.Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

kiterjesztes utan9; ase:a8; ose:aO; ose:START-

A Nyilt Lista Lista a 4. kiterjesztes utanCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: c, koltseg: 18; ose:eCsucs.nev: h, koltseg: 19; ose:cCsucs.nev: f, koltseg: 20; ose:cCsucs.nev: i, koltseg: 21; ose:c

A Zart Lista Lista a 4.Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

kiterjesztes utan14; ose:b

9; ose:a8; ose:aO; ose:START-

A Nyilt Lista Lista a 4. kiterjesztes utanCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: c, koltseg: 18; ose:eCsucs.nev: h, koltseg: 19; ose:cCsucs.nev: f, koltseg: 20; ose:cCsucs.nev: i, koltseg: 21; ose:c

A Zart Lista Lista a 4.Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

kiterjesztes utan14; ose:b

9; ose:a8; ose:aO; ose:START-

A Nyilt Lista Lista a 5. kiterjesztes utan

49

Page 51: Programozási Versenyfeladatok - Programing Contests

Csucs.nev: f,Csucs.nev: e,Csucs.nev: c,Csucs.nev: h,Csucs.nev: f,Csucs. nev: i,Csucs.nev: f,

koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:

A Zart Lista Lista a 5.Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: f,Csucs.nev: e,Csucs.nev: c,Csucs.nev: h,Csucs.nev: f,Csucs.nev: i,Csucs.nev: f,

Lista a 5.koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:

A Zart Lista Lista a 5.Csucs.nev: d, koltseg:Csucs.nev: cf koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: e,Csucs.nev: efCsucs.nev: h,Csucs.nev: f,Csucs.nev: g,Csucs. nev: i,Csucs.nev: f,

Lista a 6.koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:

A Zart Lista Lista a 6.Csucs.nev: f, koltseg:Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

16; ose:e16; ose:b18; ose:e19; ose:c20; ose:c21; ose:c22; ose:d

kiterjesztes utan16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

kiterjesztes utan16; ose:e16; ose:b18; ose:e19; ose:c20; ose:c21; ose:c22; ose:d

kiterjesztes utan16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

kiterjesztes utan16; ose:b18; ose:e19; ose:c20; ose:c21; ose:f21; ose:c22; ose:d

kiterjesztes utan16; ose:e16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

A Zart Lista Lista a 7.Csucs.nev: e, koltseg:Csucs.nev: f, koltseg:Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: c,Csucs.nev: h,Csucs. nev: f,Csucs.nev: g,Csucs. nev: i,Csucs.nev: f,

Lista a 7.koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:

kiterjesztes utan16; ose:b16; ose:e16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

kiterjesztes utan18; ose:e19; ose:c20; ose:c21; ose:f21; ose:c22; ose:d

kiterjesztes utan16; ose:b16; ose:e16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

kiterjesztes utan19; ose:c20; ose:c21; ose:f21; ose:c22; ose:d23; ose:c25; ose:c

kiterjesztes utan18; ose:e16; ose:b16; ose:e16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

A Nyilt Lista Lista a 6. kiterjesztesCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: c, koltseg: 18; ose:eCsucs.nev: h, koltseg: 19; ose:cCsucs.nev: f, koltseg: 20; ose:cCsucs.nev: g, koltseg: 21; ose:fCsucs.nev: i, koltseg: 21; ose:cCsucs.nev: f, koltseg: 22; ose:d

A Nyilt Lista Lista a 8. kiterjesztes utanCsucs.nev: h, koltseg: 19; ose:c

utan Csucs.nev: f, koltseg: 20; ose:cCsucs.nev: g, koltseg: 21; ose:fCsucs.nev: i, koltseg: 21; ose:cCsucs.nev: f, koltseg: 22; ose:dCsucs.nev: h, koltseg: 23; ose:cCsucs.nev: i, koltseg: 25; ose:c

A Zart Lista Lista a 6.Csucs.nev: f, koltseg:Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

kiterjesztes utan16; ose:e16; ose:e14; ose:b

9; ose:a8; ose:aO; ose:START-

A Zart Lista Lista a 7.Csucs.nev: e, koltseg:Csucs.nev: f, koltseg:Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

A Nyilt ListaCsucs.nev: h,Csucs.nev: f,Csucs.nev: g,Csucs.nev: ifCsucs.nev: f,Csucs. nev: h,Csucs. nev: i,

Lista a 8.koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:koltseg:

A Zart Lista Lista a 8. kiterjesztes utanCsucs.nev: c, koltseg: 18; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: c, koltseg: 14; ose:bCsucs.nev: e, koltseg: 9; ose:aCsucs.nev: b, koltseg: 8; ose:aCsucs.nev: a, koltseg: O; ose:START-CSUCS

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

50

A Zart Lista Lista a 8.Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: f, koltseg:Csucs.nev: d, koltseg:Csucs.nev: c, koltseg:Csucs.nev: e, koltseg:Csucs.nev: b, koltseg:Csucs.nev: a, koltseg:CSUCS

Page 52: Programozási Versenyfeladatok - Programing Contests

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

A Zart Lista Lista a 9. kiterjesztes utanCsucs.nev: h, koltseg: 19; ose:cCsucs.nev: c, ko1tseg: 18; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: c, koltseg: 14; ose:bCsucs.nev: e, koltseg: 9; ose:aCsucs.nev: b, koltseg: 8; ose:aCsucs.nev: a, koltseg: O; ose:START-CSUCS

A Nyilt Lista Lista a 9. kiterjesztes utanCsucs.nev: i, koltseg: 20; ose:hCsucs.nev: f, koltseg: 20; ose:cCsucs.nev: g, koltseg: 21; ose:fCsucs.nev: i, koltseg: 21; ose:cCsucs.nev: f, koltseg: 22; ose:dCsucs.nev: h, koltseg: 23; ose:cCsucs.nev: g, ko1tseg: 24; ose:hCsucs.nev: i, koltseg: 25; ose:c

A Zart Lista Lista a 9. kiterjesztes utanCsucs.nev: h, koltseg: 19; ose:cCsucs.nev: c, koltseg: 18; ose:eCsucs.nev: e, koltseg: 16; ose:bCsucs.nev: f, koltseg: 16; ose:eCsucs.nev: d, koltseg: 16; ose:eCsucs.nev: c, ko1tseg: 14; ose:bCsucs.nev: e, koltseg: 9; ose:aCsucs.nev: b, koltseg: 8; ose:aCsucs.nev: a, koltseg: O; ose:START-CSUCS

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

51

Page 53: Programozási Versenyfeladatok - Programing Contests

Függelék

Ábrák, programok listája

Fig. 1.1.1.: Fike algoritmusa Rohl módosításaival 7Fig. 1.1.2.: A lexikografikus felsorolás négy lépése 7Fig. 1.1.3.: Permutációk lexikografikusan 8Fig. 1.2.1.: Rohl algoritmusa (1978) 10Fig. 1.2.2.: Wells féle IPERM2NUM függvény (1971) IIFig. 1.3.1.: Permutációk inverziójának generálása 13Fig, 1.3.2.: A C~P átalakítást végző eljárás 14Fig. 1.3.3.: A RankrPerm eljárás 14Fig. 1.3.4.: Az rPermGen eljárás 15Fig. 1.4.1.: Az {1,2, ,n} halmaz összes részhalmazánakfelsorolása 17Fig. 1.4.2.: Bn értékei 18Fig. 1.4.3.: Az {l,2,3,4} halmaz összes partíciói és a hozzájuk tartozó kódszavak 18Fig. 1.4.4.: M. C. Er rekurzív algoritmus az {1,2, ,n} halmaz összes partíciójának generálásához 19Fig. 1.4.5.: Az Er-féle rekurzív halmaz particionáló algoritmus futási ideje néhány n-re 19Fig. 1.5.1.: Gray kódok 23Fig. 1.5.2.: Ciklikus Gray kódok 23Fig. 1.5.3.: Twiddler.pas 25Fig. 2.0.1.: Geometriai objektumok reprezentációja 27Fig. 2.1.1.: Szakaszok a sikon 28Fig. 2.1.2.: Szakaszok metszetének vizsgálata 29Fig. 2.2.1.: Pont és Poligon elhelyezkedései a sikon 31Fig. 2.2.2.: A fenti program eldönti, hogy egy adott pont egy adott poligon belsejében van e 33Fig. 2.3.1.: Ponthalmazok konvex burka 34Fig. 2.3.2.: Ponthalmaz konvex burkát előállító algoritmus 35Fig. 2.3.3.: A "csomagoló" eljárás működése 35Fig. 2.3.4.: A Konvex Burok algoritmus 38Fig. 3.1.1.: Általános kereső eljárás müködése 40Fig. 3.1. 2.: A mélységi keresés algoritmusa 40Fig. 3.1.3.: A mélységi keresés 42Fig. 3.2.1.: Az optimális keresés algoritmusa 44Fig. 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 egyhalmaz 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 30P2.2.2. Adott n szakasz, eldöntendö, hogy páronként metszík-e egymást... 30P2.2.3. Hány metszéspont ja van egy adott n csúcsú konvex poligon átlóinak 30P2.2.!. Írjunk hatékony algoritmust, amely eldönti, hogy egy pont egy konvex poligon belsejében van-e! 33P2.2.2. Írjunk olyan pascal függvényt, amely eldönti, hogy két háromszögnek van-e metszéspont ja 33P2.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 megadottpontok konvex burkát adja meg lépésenként, módosítva azt 38

52

Page 54: Programozási Versenyfeladatok - Programing Contests

Name: Public keydecryption

USSC85 - 1

Files:programinputoutput

key.paskey. inkey. 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 istransformed into an integer C. There is also an integer secret key, S, and a publicly knowninteger 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 itas 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 thep1aintext integer 40506 translates to "CBA".

Input will consist of one or more messages. Each message is represented by severa1integers. The order of these integers is as fo11ows:

Integer 1messages) .

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

Integer n+1

M < sqrt(maximum positive integer)Secret key S as described above. O<S<MEncoded blocks, C, as described above. O < C < maximum positiveinteger-1

Integer 2Integers 3 to n

The integers for each message are in free format, separated by spaces. Each line ofinput 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 theinput are sequences of non-space characters delimited by spaces. Words in the output are tobe separated by single spaces or new lines. Words must be packed as densely as possible on aline without splitting. Right justification is not required. Hint: No multiple preci sion or80ating 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

Page 55: Programozási Versenyfeladatok - Programing Contests

OUTPUT

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

Name: Krypto Player USSC85 - 2

Files:programinputoutput

krypto.paskrypto.inkrypto.out

Task:

Krypto is a Parker Brothers card game played wi th a deck containing the positi veintegers from l to 25 (some more than once). The object of the game is to combine the fivecards in your hand by addition, subtraction, mul tiplication, and division to obtain aspecific number.

Play proceeds as follows. One player is designated as the dealer. The dealer givesevery player in the game five cards face down. After alI players have received their hands,the dealer turns the next card in the deck face up so alI the players can see it. Everyonethen 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)hegoes. If the solution checks out, that player wins the hand, and the deal is passed to theleft.

)

For example, assume you were dealt 15, 9, 4, 3, and ll. The fa ce up card is a 5. Onesolution 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 orgrouping 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-upcard separated by one or more spaces. The program should print a solution for each hand inthe left-to-right format described above (use * for multiplication and / for division). Ifno 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 = 51 2 1 1 2 25 1 211 2 CANNOT BE COMBINED TO EQUAL 25

2

Page 56: Programozási Versenyfeladatok - Programing Contests

Name: Fizz-Buzz USSC85 - 3

Files:programinputoutput

fizz.pasfizz.infizz.out

Task:

Fizz-Buzz is a party game played by 2 to 12 people. The game starts when the firstplayer 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 specialrules:

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 wordinstead of the number. If a player is caught making an error, (slhe is eliminated. The lastplayer remaining is the winner.

You are to write a program that prints Fizz-Buzz tables. input to your program will bea list of number pairs. Each pair will consist of the number of columns (corresponding tothe number of players, 2 to 12) in the table and the minimum number to be processed, on oneline separated by spaces. For each table you should eject a page, print a header, and printthe sequence up to the specified maximum using the proper number of columns. Use a formatsimilar to the example shown.

Samples:

INPUT OUTPUT

3 10 THE FIZZBUZZ SEQUENCE TO 10:10 30

1 2 FIZZ4 5 FIZZBUZZ 8 FIZZ10

- new page -

THE FIZZBUZZ SEQUENCE TO 30:

1 2 FIZZ 4 5 FIZZ BUZZ 8 FIZZ 10II FIZZ FIZZ BUZZ FIZZ 16 BUZZ FIZZ 19 20FIZZBUZZ 22 Frzz FIZZ 25 26 FIZZBUZZ BUZZ 29 Frzz

3

Page 57: Programozási Versenyfeladatok - Programing Contests

Name: Asteroids! USSC85 - 4

Files:programinputoutput

roids.pasroids.inroids.out

Task:

Vapor Video is producing a new game in which the player defends the earth against anasteroid swarm with a variety of missiles which can fragment or deflect them. The task ofyour team is to wri te the program which calculates the res ul ts of each atta ck . It issufficient 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 suchthat the distance the asteroid is deflected is a linear function of its 2-velocity and thetime remaining until its y coordinate is O. abs(x) must be >= 6.3 x 10A6 meters at that timein order to miss be earth. For example, if the asteroid has an x-velocity of -7.4meters/secafter an atta ck at 10.2 days before impact, it will have x = 6.52 x 10A6 meters when y = Oand will miss the earth. If the asteroid is fragmented by the attack, it will no longer be athreat. Note that the missile will always hit the proper point on the asteroid so that itwill not ch ange the asteroid's y-velocity.

Higher level routines will keep track of the asteroids. You only have to look at theeffect of each shot. The asteroids will always be close enough to the positi ve y-axis sothat you only have to consider the x-ve loci ty. You wi II be gi ven the time to impact r theradius 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), thenew x-velocity, and the state of the asteroid: whether it is fragmented or if it will hit ormiss the earth with no further attacks.

The asteroids are aLl rock spheres with a density of 3.5 x 10A6 grams/meterA3. Thefollowing information from "The Asteroid Miner's Handbook" is alI that is needed.

Symbols:S:Radius of asteroid in metersM:Mass of asteroid in gramsW:Size of missile warhead in megaton equivalents of TNTR:Radius of crater in metersD:Depth of crater in metersF:Depth of fracture zone in metersV:Volume of crater in cubic metersdV:Change in velocity in meters/sec

M = 1.47 x 10A7SA3R=94 .5$WO. 28D=0.500RF=0.750RV =pi/2*RA2*DdV=(1.17*10A9*V)/Mif F>0.855 the asteroid is fragmented.

The input will be a sequence of lines, one line per test case, terminated by end offile. Each line has four numbers: the time in days before the asteroid crosses y = O, theradius of the asteroid in meters, the size of the missile warhead in megaton equivalents ofTNT, 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 rightside which will yield a negative increment (the single quotes are literaily included in theinput). The fields are separated by at least one blank. Each line is less than 81 characters

4

Page 58: Programozási Versenyfeladatok - Programing Contests

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 DAYS15 5000 1000 .1 ,+, RADIUS OF ASTEROID: 698 METERS2.5 30 .03 O ,+, SIZE OF WARHEAD 100 . MEGATONSINITIAL

X-VELOCITY: O. METERS/SECAlM: -FRACTURE RADIUS 257. METSRSFINAL X-VSLOCITY: -7.42 MSTSR/SSCSTATUS: MISS

TIMS TO IMPACT: 15.0 DAYSRADIUS OF ASTSROID: 5000 METERSSIZE OF WARHEAD; 1000 MSGATONSINITIAL X-VSLOCITY: 0.1 METSRS/SSCAlM: +FRACTURS RADIUS 490. METERSFINAL X-YELOCITY: 0.24 MSTSRS/SSCSTATUS: HIT

TIME TO IMPACT : 2.5 DAYSRADIUS OF ASTSROID : 30.0 MSTERSSI ZS OF WARHSAD: 03 MSGATONSINITIAL X-YSLOCITY: O METSRS/SSCAlM : +FRACTURS RADIUS: 26.6 MSTERSFINAL. VELOCITY : 103. MSTSRS/SECSTATUS: FRAGMSNTSD

Name: Jigsaw Puzzle USSC85 - 5

Files:programinputoutput

jigsaw.pasjigsaw.injigsaw.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

Page 59: Programozási Versenyfeladatok - Programing Contests

Each point represents a square centered at that point. Each piece may be rotated ortranslated as required to St it into the puzzle.

Input will consist of several shapes to be fitted. Each line of input will representone shape. Each shape is described by 12 pairs of positive integer coordinates. The shapeconsists of 12 squares centered at each input point. There are no special separators betweenthe pairs. A line of input will thus contain 24 blank separated integers consisting of 12consecutive (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 thepieces can be fit into the shape, a "picture" is to be produced of any solution showing thelocation of each piece within the shape.

Use 40 lines of output to draw the picture. Each character position on an output linewill 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 eachpicture on a separate page.

The output at (x, y) should be a blank if this square is not in the input shape, orthe 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 .

1

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

I

. ·.·.:---,I····:···I····j.···:·I ....:

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

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

'2

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

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

5

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

1· .....

:..~3 ..3 ..

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 12 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

12431144- new page -SOLUTION FOR SHAPE 2- 96 blank lines-

3322342144II

- new page -THERE IS NO SOLUTION FOR SHAPE 3

6

Page 60: Programozási Versenyfeladatok - Programing Contests

Name: Transmitter Hunting USSC85 - 6

Files:programinputoutput

trans.pastrans. intrans.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 nicespot and starts transmitting. The lookers start by taking readings with directional antennasfrom various locations. They then attempt to find the hider by driving to the position wherethe ini ti al readings tend to intersect and-use mobile equipment to home in on the radiosignal.

In an attempt to increase your hunting efficiency you have decided to write a programthat 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 reportcontaining ali intersections which are within the grid.

Input will consist of sets of readings terminated by the end-of file. Each set willconsist of three readings, with each reading on a separate 80column line. A reading willconsist of the 2 coordinate and the y coordinate of the location the reading was taken fromalong with the heading in whole degrees (O = north, 90 = east, 180 = south, 270 = west). Theelements 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 alreadings and the intersections within the 1000 by 1000 grid. Intersections may be eitherpoints 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 nointersections exist, produce a message to that effect. No intersection should appear morethan once.

Each report should be printed on a separate page. Use a format similar to the examplebelow.

Samples:

INPUT OUTPUT

100 100 O (100,100) O DEGREES100 600 180 (100,600) 180 DEGREES200 350 27 O (100,350) 270 DEGREES

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

7

Page 61: Programozási Versenyfeladatok - Programing Contests

Name: lefedés KlTE91 1

Files:programinputoutput

a.pasa.inpa.out

Task:

A számegyenesen N számpárral N szakaszt határozunk meg, amely lefedi a számegyenesmegfelelo 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 107 9 3

8 10*1 3

4 5

Name: Kocka KlTE91 2

Files:programinputoutput

b.pasb.inpb.out

Task:

Egy N (N egész) élhosszúságú kockát feldarabolunk 1 élhosszúságú kis kockákra. Ezutána 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ákkoordinátáit (kezdöpontnak valamelyik csúcspontot válasszuk, s az ebbol kiinduló három élreilleszkedo tengelyeken l-tol N-ig számozzunk meg 1 egység hosszúságú rekeszeket, így mindenkis 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

Page 62: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

4 962 2 2 8

2 2 3

2 3 2

2 3 3

3 2 2

3 2 3

3 3 2

*

2

1 1 2

1 2 1

1 2 2

2 1 1

2 1 2

2 2 1

Name: taxman KLTE91 3

Files:programinputoutput

c.pasc.inpc.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 ismegtalá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 ajá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. Ajá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, valamintaz egyes kiválasztott számoknál a gép melyik osztókat veszi ki.

9

Page 63: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

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

7 : 16 : 2 3

8 : 4

Max. pont: 14A kiválasztott számok és osztói:II : 19 : 3

6 : 2

8 : 4

10 : 5

Name: Út KLTE91 4

Files:programinputoutput

d.pasd.inpd.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 ela B ország. 8gy vállalatnak van mindkét országban egy-egy gyáregysége. Az A ország közutjainmax. 100 km/h sebességgel, míg a B országban max. 80 km/h sebességgel lehet közlekedni. Az Aorszá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ásodiksorban 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:

50 50

10 200

[ OUTPUT

155.73 krn

[INPUT

10

Page 64: Programozási Versenyfeladatok - Programing Contests

Name: Szint KLTE91 5

Files:programinputoutput

e.pase.inpe.out

Task:

Egy téglalap alakú tartományt felbontottunk adott sű rű s é qű rácsra, és megmértük atartomá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, azaztudunk-e rácspont ról szomszédos rácspontra lépkedve önmagába v i ss zat é 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 at á 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 akörön belül legyen! Szomszédos rácspontoknak tekintjük az átlós szomszédokat is. A keresettkö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ó- ésfelsohatá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ámokategy-egy szóköz választja el.

Az OUTPUT filePontosan 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 tartalmazzaannak 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ÖRBE5 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

Page 65: Programozási Versenyfeladatok - Programing Contests

Name: matrix KLTE91 6

Files:programinputoutput

f.pasf.inpf.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(2,1) a(2,2)

a(l,n)

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 48617 5 7

12

Page 66: Programozási Versenyfeladatok - Programing Contests

Name: GRAF KlTE91 7

Files:programinputoutput

g.pasg.inpg.out

Task:

Egy gráfról mondjuk meg program segítségével, hogy minimum hány szín kell ahhoz, hogya 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-egy gráf megadásakor eLö sz ö r az élek száma található,(egyik csúcs, szóköz, másik csúcs, soremelés).

egy '* , választ el egymástól.majd az élek felsorolása jön

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

Samples:

INPUT OUTPUT

3 31 2 2

2 33 1*41 2

1 33 45 1

Name: Playcard IOAG91

Files:programinputoutput

playcard.pasplaycard.inpplaycard.out

Task:

A pack of cards consists of 52 cards, which have 13 different values1,2,3,4,5,6,7,B,9,10,J,Q,K, and four different suits: Spades, Clubs, Diamonds, Hearts (Spadeand Club are black, Diamonds and Hearts are red). We have a pack of full cards, which weshuffle. 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 andcontinue pulling out cards until 3 rows of 4 cards each are completed. We now proceedchecking if among the cards, we have put on the table, there are pairs of cards whose values

13

Page 67: Programozási Versenyfeladatok - Programing Contests

give 10 as sum. If there are two cards with the value of 10 each, one of them is consideredas having value o. On the above pairs of cards we place two cards of the pack one on eachcard of the pair ). If during this phase we pulI out a J, Q or K we place this on one cardof 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 thereare no more pairs of cards with sum 10. Write a program which simulates the above procedurewith the following demands:

1. - The number N of repeti tions of the above procedure must be entered from thekeyboard. 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 cardsmust 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 proceduredescribed 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 replacedwith 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 onthe screen.

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

Name: Trees IOAG91 2

Files:programinputoutput

trees.pastrees.inptrees.out

Task:

A farmer wants to preserve a ra re class of ancient cypress trees. In order to do thathe has taken note of the position of each tree and he has decided to surround the trees withwire 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, oneof its sides being parallel to the X-axis, and he needs to know the relative location of thehouse:

(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

Page 68: Programozási Versenyfeladatok - Programing Contests

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

Output:- A sequence of M points (l<=M<=N) with the property that if we trace through thepoints 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:programinputoutput

square.passquare.inpsquare.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 numberi+1 can be assigned to the matrix posi tion wi th coordinates (z,w) according to one of thefollowing rules:

(1) (z,w)

(2) (z,w)

(3) (z,w)

(x+-3,y)(x,y+-3)(x+-2,y+-2)

The problem is:(A) Write a program that enumerates the positions ofthe 5x5 matrix for agiven starting position with thenumber 1.

(B) Compute the number of all possible enumerations for every starting position atthe 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 thefollowing positions with coordinates: (2,5) or (5,2) or (4,4). These positions are marked infigure 1 by an asterisk (*).

1 2 3 4 5

+---+---+---+---+---+1

+---+---+---+---+---+2 : 1 : : * :

+---+---+---+---+---+3

+---+---+---+---+---+: * :

+---+---+---+---+---+5 : * :

+---+---+---+---+---+

15

Page 69: Programozási Versenyfeladatok - Programing Contests

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

Name: Maximum Gang IOAG91 4

Files:programinputoutput

gang.pasgang.inpgang.out

Task:

A Police captain knows we Ll. a lL the outlaw persons of his city, as we lI as, everypossible collaboration among them. He would like to find the maximum gang of the city. Inthis case, a gang is a subset of outlaw persons so that any person in it collaborates witha Ll. others in the subset . Maximum gang means that there does not exist another gang wi thgreat 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 asinput data file an ASCII one with the followingstructure:

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 withperson j or i=j, and a(i,j)=O, otherwise. forinstance (in the case of 6 persons):

1

01101101101101101111

In this example an output can be the followingone:

A Maximum Gang is136cardinality = 4

(B) Extend the input part of the program, so that togenerate data in a random way under agiven pro-pability O < d < 1 of collaboration of outlawpersons.

(C) Using random data or input file, find the maximumgang of the city.Use the same output format as in the exampleabove ( see task A ).

16

Page 70: Programozási Versenyfeladatok - Programing Contests

Name: Let's Go To TheMovies

TUBP91 1

Files:programinputoutput

Task:

p1.pasp1.inpp1.out

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 bitshabby, far from the busy centre, so the tickets are fairly cheap 50 Ft each, otherwisenobody 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, andthe cashier can se11 them a ticket only if they either pay with a 50 Ft bill, or she cangive back the proper change, i.e. if she has at least one 50 Ft bill in the cash-box exactlywhen it is needed. If she can't give back the money, she gets really embarrassed, closes theoffice 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 arriverandomly. 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 onepositive number indicating the number of the would-be audience for the film. The outputfile, PI.OUT, shou1d contain the corresponding answers the number of the possiblesequences -- as integer numbers, one on each line. The input number will not exceed thecapa city of the cinema.

Samples:

INPUT OUTPUT

5 102 212 924

Name: MaximalSubsequence

TUBP91 2

Files:programinputoutput

Task:

p2.pasp2.inpp2.out

There is a sequence. of integer -- positive and negative numbers. Your task is towri te a program which finds a continuous subsequence where the sum of the integers ismaxirnal.

The input to the program is in a file, called P2.INP, where each line containspositive or negative integers, separated by single spaces. A sequence can span several

17

Page 71: Programozási Versenyfeladatok - Programing Contests

lines, and it is terminated with the number zero. In the file there may be several of suchsequences. 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 theinput 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 DateScribbler

TUBP91 3

Files:programinputoutput

p3.pasp3.inpp3.out

Task:

Big Bubbles Unlimited, a polynational company, sends hundreds of letters a day toevery corner in the world. Ms Pedant, the recent1y appointed Chief Public Relationist at itsnew Balmazujvaros-based headquarters, has soon discovered the diversity of date formats thecorrespondents use in their letters. (However, they never mix the various date formatswithin one letter.) As she finds it an offence against the company's appearance, she chargesyou with the task of writing the Best Almighty Date Scribbler (briefly, BADS) in Pascal. Theprogram is supposed to

1) read a tagged date conversion rule (first line), and the name of the sourceand 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'.

month; day.'dddd' .

item: year;year: 'dd' ;month: 'dd' ;day: ld' ;

I aaa 1.

'dd' .separator: '/ ' ;

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

18

Page 72: Programozási Versenyfeladatok - Programing Contests

At both sides of a date conversion rule, each 'd' matches a digi t from O to 9, andeach 'a' matches a letter from A to Z, or a to z (English alphabet). The program doesn'thave to check the validity of days and years, nor the syntax of the rules. However, it mayhave 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/ddErnestDMYdd/dd/dddd~>YMDdd-aaa-ddJudyERNEST.INP

To Ernest Lonely, Old HarbourNew Harbour, 91/10/04Ref. 05/10-31/1991Earnest,I want to see you immediately!! Call me, please, notlater than91/10/10!! I have an urgent matter to discuss withyouconcerning our holiday between 91/12/28 and 92/01/03.1 canlt gofor I'll start my new job with New World just afterXmas, on 91/12/27.Regards,Geyza

ERNEST.OUT

To Ernest Lonely, Old HarbourNew Harbour, Oct/4/91Ref. 05/10-31/1991Earnest,I want to see you immediately!! Call me, please, notlater thanOct/10/91!! 1 have an urgent matter to discuss withyouconcerning our holiday between Dec/28/91 andJan/03/92. 1 can't gofor 1'11 start my new job with New World just afterXmas, on Dec/27/91.Regards,Geyza

JUDY.INP

To Judy Lovely, Fifth WorldNocity, 04/10/1991Ref. 05/10-31/1991Hi Judy,call me, please, on 10/10/1991. 1 have an urgentbusiness matterconcerning our conference between 17/01/1992 and21/01/1992. Ormay 1 see you on 12/10/1991 during my visit to FifthWorld?With love,Geyza

JUDY.OUT

To Judy Lovely, Fifth WorldNocity, 91-0ct-04Ref. 05/10-31/1991Hi Judy,call me, please, on 91-0ct-lD. 1 have an urgentbusiness matterconcerning our conference between 92-Jan-17 and 92-Jan-21. Ormay 1 see you on 91-0ct-12 during my visit to FifthWorld?With love,Geyza

Name: Minimal Difference

Files:programinputoutput

p3.pasp3.inpp3.out

Task:

TUBP91 3

There is a decimal number containing 2n digi ts. You have to form two numbers, eachcontaining exactly n digits from the originalone, in such a way that the difference of thetwo newly forrned number be minimal. Each digit of the original number should be used onlyonce.

The input file, P4. INP, contains the original numbers, one in a line. The resul tshould be written into a file called P4.0UT, every line containing the two resulting numbersand their difference, separated by spaces.

19

Page 73: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

63960804 6400 6398 2

4159 51 49 2

Name: Pocket Calculator TUBP91 5

Files:programinputoutput

p5.pasp5.inpp5.out

Task:

Abacus Inc., the market leader manufacturer of pocket ca1cu1ators is planning todevelop a new model, which is able to work with mathematical formulae, consisting ofvariables, numeric constants, and operators. A variable can be assigned a value accordingthe 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 parenthesesare not limited by the grammar.

You, a young and gi fted employee of Abacus, are charged wi th wri ting the syntaxchecker of the new calculator. Your Pascal program should be able to check whether a formulasatisfies the syntactic rules given above.

The program reads its data from a file, P5.INP, each line containing a formula, andshould 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 theresult of the formulae.Samples:

INPUT OUTPUT

H:=(A-BI*(AtBI PASSED0:=( ( A I + (B * C * Ol I PASSEOH:=( (A-BI*(AtBI REJECTED

20

Page 74: Programozási Versenyfeladatok - Programing Contests

Name: Seven Up TUBP91 6

Files:programinputoutput

p6.pasp6.inpp6.out

Task:

The subcommittee Seven Lean Years keeps its proposal, as top secret, under seven seals. Itsmembers 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 atits 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 behigher. (The opposition is, of course, wrong by saying that in that case also the priceslook higher. )The proposal assigns the names of the seven Hungarian home-conquering chieftains to thedigits of the new-old number system. Each of the seven so-called lean digits is denoted by acharacteristic letter of these names (see below. Their outdated decimal equivalents are alsogiven 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 +7O A AA AE EOA EOAA AO O7 OA OAA OAE OEOA OEOAA OAO 0014 OOA OOAA OOAE OOEOA OOEOAA OOAO OK21 OKA OKAA EK EKA EKAA AK KTO28 KT OA KTOAA KTOAE KTOEOA KTOEOAA KTOAO KTOO35 KTOOA KTOOAA KTOOAE KTOOEOA TOOEOAA KTOOAO OT42 OTA OTAA ET ETA ETAA AT T49 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 thata lean digit may immediately be preceded by one smaller lean digit. No more than two leandigits of equal value may follow one another. A lean digit placed before a lean digit ofgreater value subtracts. A lean digit placed after a lean digit of greater or equal valueadds.According to these rules lean numbers can have alternative forms. E.g. AE can be written asEO, 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. Theoperators + (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, andevaluated 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 inputshould 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

Page 75: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

A +AA 3 = AEAE + AE 6 = AO

EO - EO Lean expr aut of rangeAM - A 341 = EMAA

MM 686 = MMTTKA - K 99 = TTA

A 1 = AAA 2 = AA

AAE Wrong lean expr! Rest: EMMMHHHT Wrong lean expr! Rest: MHHHT

Name: Papering Our Home TUBP91 7

Files:programinputoutput

p7.pasp7.inpp7.out

Task:

We would like to cover our walls with nice, trendy wallpaper, but such papers cost alot, 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 ofwalipaper may be joined only lengthwise (verticaily), no overlap is necessary. The wallpaperpieces 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 theinput file, P7.INP,

the first line gives the length and width of a walipaper roll (all rolls areidentical),the next lines describe the length and width of rectangular areas to becovered (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 bebought.

Samples:

INPUT OUTPUT

10 0.5 52.5 10 5O0.8 1.52.3 100.7 0.5O

22

Page 76: Programozási Versenyfeladatok - Programing Contests

Name: Joker RUGB91 1

Files:programinputoutput

joker.pasjoker.injoker.out

Task:

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

o O1 O

2 8038004 80005 800006 8000007 8000000

For example: the winning Joker number is 7254780; the number to check is 4253900. Only2,5 and O are digits which correspond with the winning Joker number (4 is not in the rightposition) . 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 listof 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 1601253467 0123456 O

0123456 3234578 80003234578 1244569 8801244569

Name: Calc RUGB91 2

Files:programinput

calc.pascalc1.in ... calc10.incalc.outoutput

23

Page 77: Programozási Versenyfeladatok - Programing Contests

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 notterribly complicated mathematical formulae, contained in a file. The file does not provideyou 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 amactually trying to say is that the file is in code !

Your mission, should you choose to accept it (this line is stolen from the AmericanTVseries Mission Impossible, but do not let this upset you!), is to give me the results ofthose formulae. Should you, or any of your crew be killed during this action, the Governmentwill 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 onintegers, including ° i.e. 0, 1, 2, ... ). 'Internal'is a member of the set of normal numbers.

The 10 results and the final result are guaranteed to be perfectly normal, l5-bitnonnegative values, but during calculation, anything can happen! As soon as something nastyhappens, (15-bi t overflow , non-internal operation, etc.) the resul t for the current inputfile is set to zero.

the set of natural numbersmeans that the result of the

(positiveoperation

The 10 input files are a IL ordinary ASCII-files, containing a text, built from thefollowing 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 theaddition, subtraction,

complicated mathematics you will encounter,multiplication and division, internal on

onlythe

naturalnaturalnumbers,

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 theinput file further than the first equality-sign you encounter, because you may find nonsensebeyond 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 theinput file, because only the characters of the original set of words were used. You startdecoding each file by making a histogram over the entire file, i.e. you count the number ofoccurrences of each character in the file. The one occurring most will be remapped onto thespace-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

Page 78: Programozási Versenyfeladatok - Programing Contests

Name: Bitmap RUGB91 3

Files:programinputoutput

bitmap.pasbitmap.inbitmap.out

Task:

A video digitizer produces binary images of pictures containing some simple geometricshapes. 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 willnot alI have their edges parallel to the axes). For a good understanding a rectangle hasfour corners of 900 Your task will be to identify aIL obj ects and return the bitmapcontaining only the triangles.

Since this may not be as simple a task as it seems, we will provide you with a numberof 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 aLl, shapes are ei ther triangles orrectangles, so you need not check this ; this implies for example that every occurring linewill be straight. However, since we' re tal king about a bitmap, this line may be more of astaircase'

The input file will be a textfile. The first line will contain the X- and Y-dimensionof 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 borderwill contain only O' s), that no two obj ects will touch or overlap, and that the minimumdimension 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 thetriangles that were in the original image (at the same place, of course). Have fun ...

Name: Floortiles RUGB91 4

Files:programinputoutput

floor.pasfloor.infloor.out

Task:

A eastIe needs new floortiles. The king does not like eut floortiles, so he asks touse as few cuts as possible. Eaeh room of the castIe is reetangular and there are zero ormore rectangular pillars in the rooms. No pillar touches another and no pillar touches thewall. AlI dimensions are integers ranging from 1 to 32000. The number of pillars isunlimited, as long as the pillars fit into the room. The pillars have a minimum dimension of1 by 2 length units.

The tiles used are squares and have a size of three by three length units. They can beeut at one or two times the unit length. In no case there may be a eut that is not adjacent

25

Page 79: Programozási Versenyfeladatok - Programing Contests

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

Example o,f cuts , ,

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

(0,0)

Samples:

INPUT OUTPUT

48 120 O

104 30 16

12 102 3 4 5

2 8 4 9

6 3 8 5

6 8 8 9

26

Page 80: Programozási Versenyfeladatok - Programing Contests

Name: Network RUGB91 5

Files:programinputoutput

network.pasnetwork.innetwork.out

Task:

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

As an example we will use the '835'-network that you can see on the chart: it consistsof 8 terminals, linked to 3 'calculators' and further onto S printers, in exactly the samemanner as you can see on the chart. The terminals send requests to the network, asking for acertain amount of calculation time and afterwards a certain amount of print ing time. Therequests first go into a calculator-queue before being calculate, and after calculation gointo a printer-queue before being printed . These queues both work differently, but we' IIreturn to this later.

The time is measured in arbitrary time-pulses. At time O alI queues are empty and alIcalculators and printers are available.

The input text file consists of an unknown number of lines. The first line describesthe 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 fivenumbers, 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 5has the highest priority, the amount of calculation time requested [1..20] and final ly theamount of printing time requested [1..20]. Input will be such that alI occurring times willfit 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 orderedfirst by priority (higher priorities first), then by terminal number (lower terminal numbersfirst) and last by request time (lower request times first). No terminal will put tworequests at the same time.

27

Page 81: Programozási Versenyfeladatok - Programing Contests

The calculators, when they finish processing a request, take the first request fromthe calculator-queue. If two or more calculators be come available at the same time, the onewith the lowest number takes the first request. They calculate upon a request for as long asis defined by the calculation-time of that request. Calculation can only start at the nexttime-pulse after the request is put, e.g. a request entered at time 1 will start calculationat time 2 (if the re is a calculator available, of course). This means that transferringevents 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. Whentwo calculators finish calculating at the same time, the calculator with the lowest numberputs it's printing request first.

The printers, when they finish processing a request, take the first request from theprinter-queue. If two or more printers become available at the same time, the one with thelowest number takes the first request. They print upon a request for as long as is definedby the printing-time of that request.

The input file contains the terminal requests, sorted upon request time (only upontime, no further sorting) .

The output text file should contain one line for each request, and the requests shouldoccur in the same order as in the input file. Each line should contain four numbers: thecalculator number that processes the request, the time at which calculation starts, theprinter number that processes the request and the time at which printing starts allnumbers should be separated by exactly one space.

Samples:

INPUT OUTPUT

8 3 5 2 2 1 121 1 1 10 101 2 1 10 10 3 2 2 121 3 2 12 12 1 2 5 141 4 1 10 10 1 14 5 265 10 5 1 20 2 12 3 136 10 5 1 20 3 12 4 137 10 5 1 20 2 13 1 2210 1 1 10 10 3 13 2 23

Name: Buying a house RUGB91 6

Files:programinputoutput

house.pashouse.inhouse.out

Task:

For this next problem, we' re going to plunge into the magic of 'real estate'. Sincehouseprices are rising far above the means of normal mortal souls, a solution has to befound. The solution we will concentrate upon is that of people putting their money togetherto 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 forone house (blocks are separated by one blank line). The first line contains the price of thehouse (this price, as well as all amounts of money, are guaranteed to be non-zero positiveintegers), 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

Page 82: Programozási Versenyfeladatok - Programing Contests

person: his number ("We are very discrete, Sir, everybody is anonymous !"), one or moreblanks, and the amount of money he possesses. These lines are not guaranteed to be sorted inany way.

We define a combination as a group of one or more people who are able to buy the housewhen they put their money together, but when any of the persons is taken away, they're nolonger 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 possesses10 al though they are able to buy the house, they don' t form a valid combination sinceperson 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 writethese 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

254

1 102 103 104 10

Name: Check! RUGB91 7

Files:programinputoutput

check.pascheck. incheck. aut

Task:

Since alI computer programmers know how to play chess, here is a simple problem foreveryone. Your program has to determine whether white' s king is in check, in a series ofpositions. 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 oflines. These lines contain three characters each

29

Page 83: Programozási Versenyfeladatok - Programing Contests

- the first character is from the set {'p', 'r', 'n', 'b', 'q', 'k'} and denotes thepiece whose location is being described: pawn, rook, knight, bishop, queen and kingrespectively.

- the second and third character indicate the location of this piece, coded as aletter {'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:safe:

if white's king is under attackif there is no piece threatening white's king

Ali the rules of chess apply. Note that check should be reported even if thethreatening piece is pinned. You should assume that each posi tion described in the inputfile 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 checkpe4 safe

kb8nc5bg6

kh3pf3

rb3kf8

Name: We get around ... RUGB91 8

Files:programinputoutput

tour.pastour. in, bus. intour.out

Task:

The Poucher family are on holiday in an unfamiliar part of the country and want toorgani ze some round-trip excursions. However, the only information they have on possibleroutes is a lea flet listing ali bus services to some nearby towns and their prices. ThePouchers 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 tourlist to produce a list of possible tours and the total cost of each tour. Ali the busservices are two-way and run between exactly two towns. Since this is a sight-seeingholiday, 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 willcontain 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 serviceand 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 ofblocks, each block describing a tour. A block contains a number of place names, one per

30

Page 84: Programozási Versenyfeladatok - Programing Contests

line. The first line indicates the town in which the tour must start and end. The remaininglines list the names of places which must be visi ted on the tour. These places must bevisi ted at least once in the tour, but may be visi ted in any order. Blocks are separatedfrom 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, orNo route possible.These responses should be written to TOUR.OUT, one per line

Samples:

bus.in tour.in tour.out

evergemnevele

Tour costs 7 franks.Tour costs 20 franks.Tour costs 35 franks.No route possible.

lovendegem evergem 1nevele lovendegem 1gent evergem 3gent lovendegem 4nevele gent 4gent wetterenmelle gent 2melle aalst 6wetteren aa1st 8aalst haaltert 1haaltert opwijk 5aalst opwijk 2buggenhout opwijk 3

gent

gentaalst

haaltertlovendegem

gentbuggenhout

Name: Firetruck ACMF91 1

Files:programinputoutput

a.pasa.inpa.out

Task:

The Center City fire department collaborates with the transportation department toma í nt a í n maps of the city which reflects the current status of the city streets. On anygiven day, several streets are closed for repairs or construction. tirefighters need to beable 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 singlefirestation. When a fire is reported, a central dispateher alerts the firestation of thedistrict where the fire is located and gives a list of possible routes from the firestationto the fire. You must wri te a program that the central dispateher can use to gene rateroutes 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. Theinput 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 thestreetcorner closest to the fire. The next several lines consist of pairs of positiveintegers separated by blanks which are the adj acent streetcorners of open streets. (torexample, if the pair 4 7 is on a line in the file, then the street between streetcorners 4and 7 is open. There are no other streetcorners between 4 and 7 on that section of thestreet.) The final line of each test case consists of a pair of O' s. tor each test case,

31

Page 85: Programozási Versenyfeladatok - Programing Contests

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

following sample input and

Samples:

INPUT OUTPUT

6 CASE 1:1 2 1 2 3 4 61 3 1 2 3 5 63 4 1 2 4 3 5 63 5 1 2 4 64 6 1 3 2 4 65 6 1 3 4 62 3 1 3 5 62 4 There are 7 routes from the firestation to streetcorner 6.O O CASE 2:4 1 3 2 5 7 8 9 6 42 3 1 3 43 4 1 5 2 3 45 1 1 5 7 8 9 6 41 6 1 6 47 8 1 6 9 8 7 5 2 3 48 9 1 8 7 5 2 3 42 5 1 8 9 6 45 7 There are 8 routes from the firestation to streetcorner 4.3 11 84 66 9O O

Name: Triangular Vertices ACMF91 2

Files:programinputoutput

b.pasb.inpb.out

Task:

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

x

x xx 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 groupsof these points form the vertices of certain geometric shapes. For example, the sets ofpoints {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 thisanalyze it, and determine whether the points are the vertices of one

triangular grid,of the following

'acceptable' figures: triangle, parallelogram, or hexagon. In order for a figure to beacceptable, it must meet the following two conditions:

32

Page 86: Programozási Versenyfeladatok - Programing Contests

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

Input and OutputThe 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 arelimited to the range 1 ..32767.

For each point set in the input file, your program should deduce from the number ofpoints in the set which geometric figure the set potentially represents; e.g., six pointscan only represent a hexagon, etc. The output must be a series of lines listing each pointset followed by the results of your analysis.

Samples:

INPUT OUTPUT

1 2 3 1 2 3 are the vertices of a tri angleII 13 29 31 II 13 29 31 are not the vertices of an acceptable figure26 II 13 24 26 II 13 24 are the vertices of a parallelogram4 5 9 13 12 7 4 5 9 13 12 7 are the vertices of a hexagon1 2 3 4 5 1 2 3 4 5 are not the vertices of an acceptable figure47 47 are not the vertices of an acceptable figureII 13 23 25 II 13 23 25 are not the vertices of an acceptable figure

Name: ConcurrencySimulator

ACMF91 3

Files:programinputoutput

c.pasc.inpC.out

Task:

Programs executed concurrentlyon a uniprocessor system appear to be executed at thesame time, but in reality the single CPU alternates between the programs, executing somenumber of instructions from each program before switching to the next. You are to simulatethe concurrent execution of up to ten programs on such a system and determine the outputthat they will produce.

The program that is currently being executed is said to be running, while allprograms awaiting execution are said to be ready.more than 25 statements, one per line, followedavailable are listed below.

A program consists of aby an end statement .

sequence of noThe statements

Statement TypeAssignmentOutputBegin Mutual ExclusionEnd Mutual ExclusionStop Execution

Syntaxvariable = constantprint variablelockunlockend

A variable is any single lowercase alphabetic character and a constant is an unsigneddecimal number less than 100. There are only 26 variables in the computer system, and theyare shared among the programs. Thus assignments to a variable in one program affect thevalue that might be printed by a different program. All variables are ini ti al ly set tozero.

33

Page 87: Programozási Versenyfeladatok - Programing Contests

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:

1: 32: 33: 173: 91: 91: 92: 82: 83: 213: 21

INPUT OUTPUT

3 1 1 1 1 1 1a = 4print alockb = 9print bunlockprint bend

a = 3print alockb = 8print bunlockprint bend

34

Page 88: Programozási Versenyfeladatok - Programing Contests

b = 5a = 17print aprint blockb = 21print bunlockprint bend

Name: The Domino Effect 4ACMF91

Files:programinputoutput

d.pasd.inpd.out

Task:

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

Bone # Pips Bone # Pips Bone # Pips Bone # Pips1 O O 8 1 1 15 2 3 22 3 62 O 1 9 1 2 16 2 4 23 4 43 O 2 10 1 3 17 2 5 24 4 54 O 3 II 1 4 18 2 6 25 4 65 O 12 1 5 19 3 3 26 5 56 O 5 13 1 6 20 3 27 5 67 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 identical7 x 8 grid with the appropriate bone numbers substituted for the pip numbers appearing onthat bone. An example of a 7 x 8 grid display of pi ps and a corresponding map of bonenumbers 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 111 3 2 O 1 O 3 10 10 14 7 2 2 21 231 3 2 4 6 6 5 8 16 25 25 13 21 231 O 3 2 1 1 2 8 16 15 15 13 9 95 1 3 6 O 4 5 5 12 12 22 22 5 5 26 265 5 O 2 6 O 3 27 24 24 3 3 18 1 196 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 anystandard set of dominoes and produce a map showing the position of aliIf more than one arrangement of dominoes yield the same pattern,generate a map of each possible layout.

7 x 8 layout of adominoes in the set.your program should

Input and OutputThe 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

Page 89: Programozási Versenyfeladatok - Programing Contests

set is corresponds to a legitimate configuration of bones (there will be at least one mappossible 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 anecho printing of the problem set itself. This is followed by a map label for the set andthe 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 ofpossible maps appears. At least three lines are skipped between the output from differentproblem sets while at least one line separates the labels, echo printing, and maps withinthe same problem set. A sample input file of two problem sets along with the correct outputare 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 13 2 6 5 O 4 2 O 5 4 3 6 5 3 4 65 3 6 2 3 2 O 6 O 6 O 1 2 3 1 14 O 4 1 O O 4 1 3 2 6 5 O 4 2 O5 2 2 4 4 1 6 5 5 3 6 2 3 2 O 65 5 3 6 1 2 3 1 4 O 4 1 O O 4 14 2 5 2 6 3 5 4 5 2 2 4 4 1 6 55 O 4 3 1 4 1 1 5 5 3 6 1 2 3 11 2 3 O 2 2 2 21 4 O 1 3 5 6 5 Maps resulting from layout #1 are:4 O 6 O 3 6 6 54 O 1 6 4 O 3 O 6 20 20 27 27 19 25 256 5 3 6 2 1 5 3 6 18 2 2 3 19 8 8

21 18 28 17 3 16 16 721 4 28 17 15 15 5 724 4 11 11 1 1 5 1224 14 14 23 23 13 13 1226 26 22 22 9 9 10 10

There are 1 solution (sj for layout #1.Layout #2:

4 2 5 2 6 3 5 45 O 4 3 1 4 1 11 2 3 O 2 2 2 21 4 O 1 3 5 6 54 O 6 O 3 6 6 54 O 1 6 4 O 3 O6 5 3 6 2 1 5 3

Maps resulting from layout #2 are:

16 16 24 18 18 20 12 116 6 24 10 10 20 12 118 15 15 3 3 17 14 148 5 5 2 19 17 28 26

23 1 13 2 19 7 28 2623 1 13 25 25 7 4 427 27 22 22 9 9 21 21

16 16 24 18 18 20 12 116 6 24 10 10 20 12 118 15 15 3 3 17 14 148 5 5 2 19 17 28 26

23 1 13 2 19 7 28 2623 1 13 25 25 7 21 427 27 22 22 9 9 21 4

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

Name: Hospital Facilities ACMF91 5

Files:programinputoutput

e.pase.inpe.out

36

Page 90: Programozási Versenyfeladatok - Programing Contests

Task:

County General Hospital is trying to chart its course through the troubled waters ofthe economy and shifting population demographics. To support the planning requirements ofthe hospital, you have been asked to develop a simulation program that will allow thehospital to evaluate alternative configurations of operating rooms, recovery rooms andoperations guidelines. Your program will monitor the usage of operating rooms and recoveryroom beds during the course of one day.

County General Hospital has several opera ting rooms and recovery room beds. Eachsurgery patient is assigned to an available operating room and following surgery the patientis assigned to one of the recovery room beds. The amount of time necessary to transport apatient 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 theamount 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 inwhich 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. Forexample, if rooms 2 and 4 be come available simultaneously, the next patient on the rosternot yet in surgery goes into room 2 and the next after that goes into room at the sametime. After surgery, a patient is taken to the available recovery room bed with the lowestnumber. If two patients emerge from surgery at the same time, the patient with the lowernumber will be the first assigned to a recovery room bed. (If in addition the two patientsentered surgery at the same time, the one first on the roster is first assigned a bed.)

Input and OutputThe 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 forthis 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 roomMinutes to prepare operating room for next patientMinutes to prepare recovery room bed for next patientNumber 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 asfollows:

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, whichdetermines the order in which patients are scheduled for surgery. The number of recoveryroom beds specified in any configuration will be sufficient to handie patients arriving fromsurgery (No queuing of patients for recovery room beds will be required). Computed timeswill not extend past 24:00.

Correct output shows which operating room and which recovery room bed is used by eachpatient, and the time period that the patient us es the room and bed along with a summary ofthe utilization of hospital facilities for that day. The output file consists of a set oftwo tables describing the res ul ts of the simulation run. The first table is in columnarform wi th appropriate column labels to show the number of each patient (in the order thepatient roster), the patient's last name, the operating room number, the time surgery beingsand ends, the recovery bed number and the time the patient enters and leaves the recoveryroom bed.

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

37

Page 91: Programozási Versenyfeladatok - Programing Contests

indicates the facility type (room or bed), the facility number, the number of minutes usedand percentage of available time utilized. Available time is defined as the time in minutesfrom the starting time for 1st surgery of day to the ending time of the last patient in arecovery 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 EndJones ------------------------------------------------------28 140 1 Jones 1 7:00 7:28 3 7:33 9:53Smith 2 Smith 2 7:00 9:00 1 9:05 12:25120 200 3 Thompson 3 7:00 7:23 2 7:28 8: 43Thompson 4 Albright 4 7:00 7:19 1 7:24 8: 4623 75 5 Poucher 5 7:00 9:13 5 9:18 12:47Albright 6 Comer 4 7:34 8:48 4 8:53 10:3419 82 7 Perry 3 7:38 9:11 2 9:16 12:24Poucher 8 Page 1 7: 43 9:34 6 9:39 13:22133 209 9 Roggio 4 9:03 10:12 9 10:17 12:19Comer 10 Brigham 2 9:15 9:57 8 10:02 ll: 2174 101 II Nute 3 9:26 9: 48 7 9:53 ll: 04Perry 12 Young 5 9:28 10:06 3 10:11 12:3193 188 13 Bush 1 9:49 10:15 10 10:20 12:21Page 14 Cates 3 10:03 12:03 8 12:08 16:16III 223 15 Johnson 2 10:12 11:38 4 ll: 43 14: 44Roggio 16 White 5 10:21 11:53 7 ll: 58 14:1869 122Brigham Faci1ity Uti1ization42 79 Type # Minutes % UsedNute -------------------------22 71 Room 1 165 29.68Young Room 2 248 44.6038 140 Room 3 258 46.40Bush Room 4 162 29.1426 121 Room 5 263 47.30Cates Bed 1 282 50.72120 248 Bed 2 263 47.30Johnson Bed 3 280 50.3686 181 Bed 4 282 50.72White Bed 5 209 37.5992 140 Bed 6 223 40.11

Bed 7 211 37.95Bed 8 327 58.81Bed 9 122 21.94Bed 10 121 21. 76Bed II O 0.00Bed 12 O 0.00

Name: Message Decoding ACMF91 6

Files:programinputoutput

f.pasf.inpf.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 partcontains a pattern that represents the message. You must write a program that can decodemessages under such a scheme.

The heart of the encoding scheme for your program is a sequence of "key" strings ofO's and l's as follows:

0,00,01,10,000,001,010,011,100,101,110,0000,0001, ... ,1011,1110,00000,

38

Page 92: Programozási Versenyfeladatok - Programing Contests

The first key in the sequence is of length 1, the next~ are of length 2, the next 7of length 3, the next 15 of length 4, etc. If two adjacent ~éys have the same length, thesecond can be obtained from the first by adding 1 (base 2). Notice that the re are no keysin the sequence that consist only of l's.

( O)

The keys are mapped to the characters in the header in o rd.er .is ma pp ed to the first character in the header, the second

That is, theto

first keythe secondkey (00)

character in the header, the kth key is mapped to the kthexample, suppose the header is:

character in the header. For

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

are to be ignored. The message is divided into segments.give the binary representation of the length of the keys

possibly carriage returns, whichThe first 3 digits of a segmentin 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 thelength 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 thekeys 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 OutputThe 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. Thelength of the header is limited only by the fact that key strings have a maximum length of7 (lll in binary). If the re are multiple copies of a character in a header, then severalkeys will map to that character. The encoded message contains only O's and l's, and it isa legitimate encoding according to the described scheme. That is, the message segmentsbegin with the 3-digit length sequence and end with the appropriate sequence of l's. Thekeys in any given segment are alI of the same length, and they alI correspond to charactersin the header. The message is terminated by 000. Carriage returns may appear anywherewithin 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 correctoutput are shown below.

Samples:

INPUT OUTPUT

TNM AEIOU TAN ME0010101100011 ##*\$101000100111011001111000$#**\0100000101101100011100001000

Name: Code Generation ACMF91 7

Files:programinputoutput

g.pasg.inpg.out

39

Page 93: Programozási Versenyfeladatok - Programing Contests

Task:

Your employer needs a backend for a translator for a very SIC machine (SimplifiedInstructional Computer, apologies to Leland Beck). Input to the translator will bearithmetic 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 theoperand is either an identifier or a storage location.

L load the operand into the registerA add the operand to the contents of the registerS subtract the operand from the contents of the registerM multiply the contents of the register by the operandO divide the contents of the register by the operandN negate the contents of the registerST store the contents of the register in the operand location

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

Input and OutputThe input file consists of several legitimate postfix expressions, each on a separate

line. Expression operands are single lettersj) and unary negation (@).

and operators are the normal arithmeticoperators (+, =, r , Output must be assembly language code thatmeets the following requirements:

1. One instruction per line with the instruction mnemonic separated from theoperand (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 begenerated (given the above restrictions).

A sample input file and corresponding correct output are on the reverse of thispaper.

Samples:

INPUT OUTPUT

AB+CD+EF++GH+++ LAAB+CD+ A B

ST $1L CA DST $2L EA FA $2ST $2L GA HA $2A $1

L AA BST $1L CA DNA $1

40

Page 94: Programozási Versenyfeladatok - Programing Contests

Name: Bit Twiddler USSC92 1

Files:programinputoutput

bit.pasbit.inbit. aut

Task:

A Gray code is a series of bit patterns in which successive values in the code differin only one bit position

For example, the following 3-bit Gray code could be used to encode the digits from Othrough 7:

GC Decimal000 O100 1101 2

001 3Oll010 5

llO 6

III 7

This example is only one of a number of possible Gray codes for3-bi t values Gray codes are commonly used when analog data must besampled and then converted to digital form. Since only one bit changesbetween the successive values in the code, ambiguity is reduced whenthe conversion must be carried out on ana log data which is at thethresholds between two potential digital values.

This example is only one of a number of possible Gray codes for 3-bit values Graycodes 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 reducedwhen the conversion must be carried out on analog data which is at the thresholds betweentwo potential digital values.

A special property of certain Gray codes is circularity, i.e. the bit pattern used toencode the first and 1 values also differ in exactly one bit position. Since this is not thecase in the above Gray code, it is not circular 3-bit circular Gray code is shown below.

Gray Code Decimal Equivalent000 O001 1011 2

010 3llO 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: thefrequency with which a bit position flips its value half of the frequency of the bitposition to its immediate right - thus the rightmost bit varies the most frequent and theleftmost bit varies the least of ten . Your task is to develop a program which can answerinquiries aboutD circular Gray codes of size 1 to 15 bits (inclusive) generated in thismanner. These inquiries will ask you to generate the bit patterns used to encode a subrangeof the integer values represented by the circular Gray code of a cer1 size. Note that onlythe non-negative integer values starting from zero will be encoded.

INPUT

41

Page 95: Programozási Versenyfeladatok - Programing Contests

The input to this program will consist of a series of inquiries in a text file. Eachinquiry wi)l occur on a line by and will consist of three integers (separated by at leastone 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 theintegers from O to 3 the 2-bit circular Gray code; the inquiry: 5 24 19 means to display thebit 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, thecode table is always printed in a order, regardless of the original order of the rangeintegers. The output resulting from each inquiry m separated by three blank lines.

Samples:

INPUT OUTPUT

2 O 3 Decimal Value 2-Bit Code5 24 1937 8 13 O 008 2 6 1 Ol4 36 41 2 II

3 10

Decimal Value 5-Bit Code

19 1101020 1111021 1111122 1110123 1110024 10100

LENGTH ERROR: 37 Bits Requested

Decimal Va1ue 8-Bit Code

2 000000113 000000104 000001105 000001116 00000101

RANGE ERROR: 4 Bits Cannot Encode 36 to 41

Name: Tempus Fugit USSC92 - 2

Files:programinputoutput

tempus.pastempus.intempus.out

Task:

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

42

Page 96: Programozási Versenyfeladatok - Programing Contests

During the week, she collects appointment requests for two weeks in advance in theorder that they made. Your program will process the requests in the same order, e.g. givingpriority to those requests were made the earliest. After running your program, she willconfirm the scheduled appointments and reschedule those appointments that the program couldnot arrange for her.

She asks that your program schedule her appointments in ten-minute blocks that beginon the hour ten-, twenty-, thirty-, forty-, and fifty-minutes past the hour. Any requeststhat 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:30a.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 scheduledappointment so that appointments occur in immediate succession. The ten-minute break willoccupy the next ten-minute block on schedule. Ten-minute breaks are not to be added forappointments which can be scheduled to end at 12:30 p. 5:00 p.m. No appointment is permittedto extend into the lunch period, or to be scheduled to begin during the period. She wouldlike 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 theoriginal request and include the ten-minute breaks which follow the adj usted appointmenttimes) . Thus the appointment request 10:15 a.m. to 10:30 a.m. contributes 20 minutes to thefour-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 eachsuccessive day of the week, scheduling it on first day that it fits: if an appointmentcannot be scheduled at. 10:00 a.m. on Wednesday your program would try to schedule it onThursday 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 ofthe day). If your program cannot schedule the appointment in this ma nrie r , the name of theperson requesting the appointment should added to the list of appointments that could not bescheduled.

INPUTThe 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, theday field occupies the next three character posi tions, and the remaining two fields eachconsist of a pair of integers. The name field will contain ten alphanumeric characters andthe day field will contain the three characters MON, TUE, WED, THU, or FRI. Following theday will be two times: the starting time of an appointment request, and its duration. Bothtimes consist of two integers, hours followed by minutes. For example, the appointmentrequest JOHNSTONE TUE 09 15 1 30 means that Johnstone requests an appointment for theTuesday of that week starting at 9:15 a.m. for one hour and thirty minutes. Since theschedule is in ten-minute blocks, your program would attempt to schedule this appointmentfor Tuesday from 9:10 a.m. to 10:50 a.m. (adding 1 hour and 40 minutes to the totalappointment time on Tuesday. Your program may assume that a I.L fields in an appointmentrequest will contain legitimate data and that times will be express ed in terms of themaximal number ofhours (9:15 a.m. will always be 09 15 rather than 08 75 and ninety minuteswill always be 1 30 rather than O 90).

Your output will consist ofa schedule for the week followed by a summary listing thenames of those people whose appointments could not be scheduled during this time. Days withno scheduled appointments should be note.

43

Page 97: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

Johnstone TUE 09 15 1 30 APPOINTMENT SCHEDULE FOR THE WEEKPeterson MON 09 00 O 30McKeever FRI 09 30 1 00 MONDAYGarzarelli THU 10 45 O 20 Peterson 9:00 to 9:30Tucker MON 10 00 2 30 Tucker 10:00 to 12:30Davis MON 02 30 1 00 Davis 2:30 to 3:30Corrigan MON 02 00 O 15Trump WED Ol 00 3 00 TUESDAYLogan THU 09 45 1 05 Johnstone 9:10 to 10:50Schulman THU II 10 O 30 Corrigan 2:00 to 2:20 O

WEDNESDAYNo Appointments Scheduled

THURSDAYGarzarelli 10:40 to 11:10

FRIDAYMcKeever 9:30 to 10:30Schulman ll:10 to ll:4O

APPOINTMENTS COULD NOT HE SCHEDULED FOR

TrumpLogan

'(

Name: Stellar Speller USSC92 - 3

Files:programinputoutput

stel.passtel.instel.out

Task:

The object of a Stellar Speller puzzleis to locate words that have been hidden inthe puzzle diagram. An example of a StellarSpeller puzzle diagram is given to thebelow

Words are forrned by starting at anyletters and following one of the connectinglines to another letter, continuing until aword has been spelled completely.

Letters in the diagram can be reusedwithin the same word, but you may notremain the on letter and use it twice insuccession nor may you jump over letters inorder to form a words. For example, thewords GRID, BURDEN, LUGGAGEappear in the puzzle shown,GRIND, BUGLE, RIDDEN do not.

legitimatelybut the words

A Stellar Speller puzzle always contains precisely thirteen letters interconnected inthe exact manner as shown above. Wri te a program which can determine whether or not eachword of an input list is hidden in agiven Stellar Speller puzzle diagram.

INPUT

44

Page 98: Programozási Versenyfeladatok - Programing Contests

The input data for this program consists of a series of puzzle sets. One puzzle setcontains three parts: the puzzle characters, the number of words to be verified, and a listof those words.

The puzzle characters will appear on the first line of the puzzle set starting in thefirst character position They will be given in top-to-bottom, left-to-right order - thus thesample puzzle would appear in the input data as the single line ASBSNGUDLISGR. Onlyuppercase alphabetic characters will appear in a puzzle.

The number of words in the verification list will be given as a positive integer onthe second line of the puzzle set. The verification list will contain at least one word andno more than twenty words.

The verification list will begin on the third line of the puzzle set. Sach word in theverification 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 fifteencharacters in length.

You may assume that ali input data adheres to the standards outlined above - no errorchecking of the input data is necessary for this problem. There are an unknown number ofpuzzle sets in the input file.

OUTPUTThe 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 wordsthat appear and do not appear in the puzzle. A blank line must separate the output fromconsecutive puzzle sets.

Samples:

INPUT OUTPUT

AEBENGUDLIEGR PUZZLE #110 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLEGRIDBURDEN GRID RIDDENRIDDEN BURDEN BEANREUBEN REUBEN BUGLEBEAN LUGGAGE GRINDBUGLE DIRE AGELESSGRINDAGELESSLUGGAGEDIREABCDEFGHIJKLM PUZZLE #21 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLEFILM

FILM

IOCBDTARGEFMS PUZZLE #39 WORDS APPEARING IN PUZZLE WORDS NOT APPEARING IN PUZZLETARGETSTART AS TARGETAS DREAMS STARTRIOT ERASER RIOTDREAMS DREARY FACESDREARY DOORSFACESERASERDOCRS

Name: Railroad Safety ODUN92 1

Files:

programinputoutput

railroad.pasrailroad.inprailroad.out

45

Page 99: Programozási Versenyfeladatok - Programing Contests

Task:

Consider the following street/railroad crossing. There are two parallel tracks crossingsing 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 arereleased. You are asked to program the controller for a safety traffic gate system at therailroad crossin

tor specificity, suppose we use thenumbered TI and T2. Sensors for each track

following naming conventions. The tracks areare SO and SI. Sensors send information to thee

controller when they are first pressed and when they are released. Trains can travel eitherdirection on either track; however, may assume that trains will not reverse direction in themiddie 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 ofthe sensors (track_no, sensor_no, [P I R]) Where track no is TI, or T2, sensor no is SO orSI, 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 fourpossibili 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 currentlyno trains and a Ll switches are released, then you could not receive the signal - T2 SOreleased.

Samples:

INPUT OUTPUT

TI SO PressedTI SI PressedTI SI PressedTl SO ReleasedQ

crossing gates closecrossing gates remain closedcrossing gates remain closedcrossing gates open

Name: Interval Arithmetic ODUN92 2

Files:

programinputoutput

inter.pasinter.inpinter.out

Task:

Compilerschecks array

for Pascal and many other languages are supposed to gene rate code thatsubscripting expressions for possible out-of-range violations.

tor example, the codeVAR

J: integer;A: ARRAY [1 ..30] Ot INTEGER;

BEGINREAD(J) ;A[J] :=0;

should behave as if the final statement actually were

IF J > = 1 and J < = 30 THENA[J] :=0

46

Page 100: Programozási Versenyfeladatok - Programing Contests

ELSESIGNAL_AN_ERROR;

Clearly, this extra codeprogram. Smart compilers will

increases both the space and time required by the runningtherefore only generate this checking code when actually

necessary.For example, in the program

VARJ: 1. .10;A: ARRAY [1..30] OF INTEGER;

BEGINREAD (J);A[2*J+5] :=0;

no special checks are necessary for the array subscript, because the READ statementwill check to be sure that the number just read is actually in the range 1. .10 beforeassigning 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 performssingle interval arithmetic operations on integers under the operations of addition,subtraction, multiplication, and division.

InputThe 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 valuesdenoting the "Y range". The third line will contain one of the characters '+', '*', or'/ ' .

OutputYour 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 isany number drawn from the Y range, and op operator in the third line.

NOTESIgnore the possibility of calculations overflowing the largest/smallest possible

integer. Even if zero is contained within the Y range, assume zero is never actually usedfor a y value in "x / y" problems.

Samples:

INPUT OUTPUT1 10 -9 II

-10 1 -8 8+-1 8-10 2/

Name: The Cat' s Stroll ODUN92 3

Files:

programinputoutput

cat.pascat.inpcat.out

47

Page 101: Programozási Versenyfeladatok - Programing Contests

Task:

8very morning, a small cat roams the city for some time, eventual returning right backwhere he started Being arather superstitious creature, he never cross es his own pathduring one of these walks. (The cat is, of course, black, and everyone knows that it's badluck to have black cat cross your path.)

In this part of the ci ty the ci ty blocks are laid out as perfect squares. Wri te aprogram to determine the area enclosed by the cat's walk.

INPUT8ach 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.

OUTPUTThe 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: NetworkConstruction

ODUN92 4

Files:

programinputoutput

network.pasnetwork.inpnetwork.out

Task:

n different databases are distributed over n locations. These locations are to benetworked so that every database can be accessed from any location. Given a set of pairs oflocations 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

Page 102: Programozási Versenyfeladatok - Programing Contests

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 . Theremaining 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:

INPUT41 2O 8 10 308 O 20 1010 20 O 5

30 10 5 O

OUTPUTconnections: 1-2 1-3 3-4 cost: 23

Name: Code ODUN92 5

Files:

programinputoutput

code.pascode.inpcode.out

Task:

A set of words is to be transmitted as messages. To save transmission time we want torepresent each word by one of the letters in the word such words will be uniquelyrepresented. Devise an algorithm to test if such representation is possible for a given setof 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:

INPUTININNONNOSAWWASTODAYHANDSOME GUY

OUTPUT

Yes

NO

S SAWA WASD TODAYM HANDSOMEU GUY

49

Page 103: Programozási Versenyfeladatok - Programing Contests

Name: The Thief ofBaghdad

TUBP92 - 1

Files:programinputoutput

a.pasa.data.rest

Task:

The Baghdad Office Building is on fire. On each floor of this high-rise building (atmost 150 floors, numbered from 1 to 150) there is a sack of gold coins. Your task is todetermine the maximum number of coins that can be safely retrieved subject to the followingconditions:

l.

2.

3.

4.

You must use the elevator which moves at a speed of 10 floors per minute.You are in the elevator on the first floor when the fire starts.The elevator cannot safely pass through a floor which is on fire.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 areassumed to have left that floor.

The input consists of series of numbers. Each series starts with an integer specifyingthe floor on which the fire starts, followed by pairs of integers specifying a floor numberand the number of coins on that floor. Floor numbers can occur in any order. In case a floornumber occurs more than once the last occur rence should be accepted . Other floors areassumed to have no coins. A single O floor number indicates the end of one series. The inputends when the file ends.

The output should contain a series of numbers equal to the coins retrieved.

Samples:

INPUT OUTPUT

17 713 15 6 8 4 3 5 8 la 7 9 9 15 7 13613 9 17 8 16 II 18 9 21 8 14 5 oo 532

3 15 6 8 4 3 5 8 la 7 9 9 15 713 9 17 8 16 II 18 9 21 8 14 522 7 30 4 26 5 27 7 28 6 31 529 4 OO O31 2 2 3 3 4 O

50

Page 104: Programozási Versenyfeladatok - Programing Contests

Name: Urban Elevations TUBP92 - 2

Files:programinputoutput

See ACMF92-7

Name:

b.pasb.datb.res

Triangular Vertices TUBP92 - 3

Files:programinputoutput

See ACMF91-2

Name:

c.pasc.datc.res

The Snake in theGrass

TUBP92 - 4

Files:programinputoutput

Task:

d.pasd.datd.res

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

Page 105: Programozási Versenyfeladatok - Programing Contests

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 ° °O 2 ° 1

1 O 1 1

1 3 2 1

2 ° 2 2

3 1 2 3

3 2 3 3

4 5 NO3

2 2

° O

3 2

52

Page 106: Programozási Versenyfeladatok - Programing Contests

Name: Wetlands of Florida TUBP92 - 5

Files:programinputoutput

e.pase.date.res

Task:

A construction company owns a largeRecently, the company decided to develophowever, it was revealed that the land,

piece of real estate within the state of tlorida.this property. Upon inspection of the property,

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 notfamiliar with wetlands of tlorida. The situation was very grave and the owners not knowingthat such bodies of water can be converted to beautiful lakes that will increase the valueof the land around them, were about to abandon the construction project. tortunately, thisfact was brought to the owners' attention by a smart graduate student, who worked for thecompany and consequently the construction project started.

The engineers divided the construction site by a grid into uni form square cells suchthat each square entirely contained either water or land. (How they did it, of course, isanybody'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 thelake containing that cell." An area is measured by the number of grid cells it contains. Youare to write a program to answer this question!

The input consists of O < n <- 99 lines, each containing O < m <- 99 character longsequence of "L"s and "W"s, followed by k > O lines, each containing a pair of integers i andj. The first n lines will represent the n by m grid covering the land where a "W"I"L" at thecth character of the rth line indicates waterland within the cell at row r and column c ofthe grid. The pairs of integers on the last k lines, each represent the row and columnnumbers of some grid cell that contains water.

The output for each pair of integers, i and j, on the last k lines of input, consistsof 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 12LLWWLLWLL 3LWWLLLLLLLWWWLWWLLLLLWWWLLLLLLLLLLLLLLLWWLLWLLLLLWLLLLLLLLLLLLL3 27 5

Name: Arbitrage TUBP92 - 6

Files:programinputoutput

f.pasf.datf.res

53

Page 107: Programozási Versenyfeladatok - Programing Contests

Task:

The use of computers in the finance industry has been marked with controversy latelyas programmed trading - designed to take advantage of extremely small fluctuations inprices - has been outlawed at many Wall Street firms. The ethics of computer programming isa fledgling field with many thorny issues.

Arbitrage is the trading of one currency for another with theadvantage of small differences in order to achieve a profit. For example,

hopes of takingif $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.00and 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 canyield a profit as described above.

To result in successful arbitrage, a sequence of exchanges must begin and end with thesame curreney, but any starting currency may be considered.

The input file consists of one or more conversion tables. You must solve the arbitrageproblem 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 ofthe 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 tablemissing (these are assumed to have value 1.0). Thus the first row of the tab1e representsthe conversion rates between country 1 and n-1 other countries, i.e., the amount of currencyof 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 nand n lines representing the conversion table.

For each table in the input file you must determine whether a sequence of exchangesexists 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 aprofit. If the re is more than one sequence that resu1ts in a profit of more than 1 percentyou must print a sequence of minimal length, i.e., one of the sequences that uses the fewestexchanges of currencies to yield a profit. If there is more than one sequence of the samelength, you must print them alI. Circular rotations of sequences do not count as differentsequences, 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 ofthe 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 tsin a profit. The sequence is printed as a sequence of integers with the integer irepresenting the line number i of the conversion table (country il. The first integer in thesequence is the country from which the profiting sequence starts. This integer also ends thesequence.

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 11.2 0.890.88 5.1Ll 0.15

54

Page 108: Programozási Versenyfeladatok - Programing Contests

4

3.10.212002.112

2.00.45

0.00230.00353180.559

0.089

Name:

0.358.1310.339

0.06111no sequence exists

3

3

2

1

1

1

2

1

1

1

2

2 3

Kombináció Kl TE92 - 1

Files:programinputoutputr:

\Task:

a.pasa.inpa.out

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 ésk kisebb mint 100.)

Az OUTPUT file:Soronként közli az egyes kombinációkat, a kü Lönbö zö

tartalmaz.

Samples:

esetek kö zö t t egy üres sort

INPUT OUTPUT

3 2 124 3 13

23

123124134234

Name: Prím Kl TE92 - 2

Files:programinputoutput

b.pasb.inpb.out

55

Page 109: Programozási Versenyfeladatok - Programing Contests

Task:

A feladat olyanintervallumban megkeresitulajdonságokkal:

- Ha a számnak elhagyjuk a legkisebb helyiértékű jegyét, akkor az így kapott számismét prím. Megismételve ezt a rnűve Let e t; ismét prímet kapunk, s ez folytatható egészenaddig, míg már csak egy egyjegyű számot vizsgálunk (természetesen ennek is prímnek kell

program írása, amely a természetesaz összes olyan prímszámot, amely

számok halmazánrendelkezik a

egy zártkövetkezo

lenni) .Ugyanez a

számjeggyel kezdjük.tulajdonság igaz r á , ha az e Löbb i eljárást

( Az 1 számot nem tekintjük prímnek.)a legnagyobb helyiértékű

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 adottintervallumban nincs megfelelo szám, akkor a NINCS szó szerepeljen annál az esetnél.

Samples:

INPUT OUTPUT

la 20 NINCS15 30

2327

Name: Gráf KLTE92 - 3

Files:programinputoutput

c.pasc.inpc.out

Task:

A feladat olyan programhurkokat, illetve megállapítja,amelyen egy csúcsból elindulva,a kiindulási csúcsba .)

írása, amelyhogya gráf

egy adott irányítatlanhurokmentes. (Huroknak

gráfban felderíti aolyan utat nevezünk,

mindig különbözo éleken és csúcsokon haladva visszaérkezünk

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úcsokszámát, majd soronként az élek megadását a két csúcs sorszámával melyeket az él összeköt. Acsúcsokat természetes számokkal jelöl j ük , l-tol N-ig, ahol N a csúcsok száma (N < laO) (Kétcsúcs között legfeljebb egy él van).

adjonhurkot

Az OUTPUT file:Tartalmazza a hurkok leírását, minden hurkot kü l ön sorban adjonmeg, hogya legkisebb indexű csúcsból kiindulva valamely irányba

alkotó csúcsokat (a kiindulásul vett csúcsot adjuk meg a

meg. Egy hurkot úgyhaladva felsorolja a

sor elején és végén

56

Page 110: Programozási Versenyfeladatok - Programing Contests

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

Samples:

INPUT OUTPUT

5 HUROKMENTES1 23 2 1 2 3 1

2 4 1 2 3 4 1

5 4 1 4 3 1

*4

1 23 24 3

1 4

1 3

Name: Kocka KLTE92 - 4

Files:programinputoutput

d.pasd.inpd.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 ö szi nü festék: kék (k), piros (p) és zöld lz). A kockamindegyik lapját befestjük a három szín valamelyikével.

2 43~

+-5

6

Mivel a kockának 6 lapja van, a számozott lapú kockákat 729 féleképpen lehetbe fest eni . Ha azonban el tekintünk a lapok számozásától, akkor jóval kevesebb lehetoségvan,mivel a kockát a tengelyei körül el lehet forgatni. Az eredeti 7291ehetoség közülazokat azonosnak tekintjük, melyeket t et sz ö 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 nemmegengedett)

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 eLe Lö en , a második 6 karakter pedig egy másik kockát reprezentál. Aprogramnak el kell döntenie, hogy ez a két festési mód azonos-e az el öbb í, értelemben vagysem.

57

Page 111: Programozási Versenyfeladatok - Programing Contests

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 OUTPUTpkzzzppzzkzp AZONOS

pppkkkppkkkp NE:MAZONOS

Name: Szines gráf KLTE92 - 5

Files:programinputoutput

e.pase.inpe.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 et 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 OUTPUT5 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

Page 112: Programozási Versenyfeladatok - Programing Contests

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:programinputoutput

f.pasf.inpf.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 amra 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 et 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

Page 113: Programozási Versenyfeladatok - Programing Contests

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

Files:programinputoutput

g.pasg.inpg.out

Task:

Adott R raksúlyú teherautóval el akarunk szállítani az A pontból a B pontba n dbtovább nem osztható csomagot, melyeknek súlyai sl, s2, s3, sn. A feladat olyanprogram írása, amely meghatározza, hogy mennyi az a legkevesebb számú forduló, amellyel ellehet 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:

10 1 1 2 5 8 9

I INPUT

Name: Permalex RUGB92 1

Files:programinputoutput

a.pasa.inpa.out

Task:

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

aabc 1 acab 5 bcaa 9

aacb 2 acba 6 caah 10abac 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 orderedsequence of permutations of its constituent characters. Note that numbers of permutationscan get very large; however we guarantee that no string will be given whose position is morethan 2~31-1 = 2,147,483,647.

60

Page 114: Programozási Versenyfeladatok - Programing Contests

Input will consist of series of lines, eachwill consist of up to 30 lower case letters,terminated by a line consisting of a single #

notline containing one string.necessarily distinct. The

Each stringfile will be

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

Samples:

INPUT OUTPUT

bacaa 15abc 1cba 6#

Name: Caesar Cypher RUGB92 2

Files:programinputoutput

b.pasb.inpb.out

Task:

One of the earliest encrypting systems is attributed to Julius Caesar: if the letterto be encrypted is the Nth letter in the alphabet, replace it with the (N+K)th where K issome fixed integer (Caesar used K=3). We usually treat a space as zero and all arithmetic isthen 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 valuesof K. This process is aided by knowledge of the language, since then one can determine whenthe decrypted text forms recognizable words. If one does not know the language, then adictionary would be necessary.

Write a program that will read' in a dictionary and some encrypted text, determine thevalue 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 theabove method. The most suitable value of K will be the one which produces the most matcheswith the words in the dictionary.

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

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

61

Page 115: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

THIS ATTACK ZORRO AT DAWNDAWNTHATTHEZORROOTHERATTHING

BUUBDLA PSSPABUAEBXO

Name: Orchard Trees RUGB92 3

Files:programinputoutput

Task:

c.pasc.inpc.out

An Orchardist has planted an orchard in a rectangle with trees uniformly spaced inboth directions. Thus the trees form a rectangular grid and we can consider the trees tohave integer coordinates. The origin of the coordinate system is at the bottom left of thefollowing 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 havecoordinates 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 giventriangle. 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 inthe triangle.

62

Page 116: Programozási Versenyfeladatok - Programing Contests

Input will consist of a series of lines. Each line will contain 6 real numbers in therange 0.00 to 100.00 representing the coordinates of a triangle . The entire file will beterminated 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 forthat 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:programinputoutput

d.pasd.inpd.out

Task:

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

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

IE

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

l--~--c--D -- E -- H --~,---1 1

I /'------.1 IA --- B ---C --O G --F H --E

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 bandwidthof 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, theinput will consist of a series of records separated by ';' Each record will consist of a

63

Page 117: Programozási Versenyfeladatok - Programing Contests

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

and at

Output will consist of one line for each graph, listing the ordering of the nodesfollowed by an arrow (-» and the bandwidth for that ordering. All items must be separatedfrom their neighbors by exactly one space. If more than one ordering produces the samebandwidth, then choose the smallest in lexicographic ordering, that is the one that wouldappear 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:programinputoutput

e.pase.inpe.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, butmost 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 thecolours, so we will presume the following ordering: •••< • < '" < • INote that because mostcharacter sets do not recognize these symbols, from now on we will use the moreconventional 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 theysit at the points of the compass they name. One player is designated the dealer and shedeals one card to each player starting with the player on her left and proceeding clockwiseuntil 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 letterrepresenting the dealer IN, E, S, W) followed by two lines representing the deck as shownbelow. 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 setwill 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

Page 118: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

N s: C3 cs C7 CT CJ D9 DT DJ S3 SK H2 H9 HTCQDTC4D8S7HTDAH7D2S3D6C6S6D9S4SAD7H2CKHSD3CTS8C9H3C3 W: C2 C4 CK D4 DS D6 DQ DA S4 S8 ST SJ H8DQS9SQDJH8HAS2SKD4H4SSC7SJC8DKCSC2CAHQCJSTH6HKH9DSHJ 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:programinputoutput

f.pasf.inpf.out

Task:

The Government of Impecunia has decided to discourage tertiary students by making thepayments of tertiary grants a long and time-consuming process. Each student is issued astudent ID card which has a magnetically encoded strip on the back which records the paymentof the student grant. This is initially set to zero. The grant has been set at 40$ per yearand is paid to the student on the working day nearest to his birthday. (Impecunian societyis still somewhat medieval and only males continue with tertiary education.) Thus on a anygiven working day up to 25 students will appear at the nea rest office of the Department ofStudent Subsidies to collect their grant.

The grant is paid by an Automatic Teller Machine which is driven by a reprogrammed8085+1/2 chip originally designed to run the state slot machine. The ATM was built in theState workshops and is designed to be directly to rob. It consists of an interior vaultwhere it holds a large stock of $1 coins and an output store from which these coins aredispensed. To limit possible losses it will only move coins from the vault to the outputstore when that is empty. When the machine is switched on in the morning, wi th an emptyoutput store; it immediately moves 1 coin into the output store. When that has be endispensed 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 thatstudent by writing the new total on the card. If the student has not received his fullgrant, he remaves his card and rejoins the queue at the end. If the amount in the store pluswhat the student has already recei ved comes to more than 40$, the machine only pays autenough to make the total up to $40. Since this fact is recorded on the card, it is pointlessfor the student to continue queuing and he leaves. The amount remaining in the store is theavailable 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 studentsleave the queue.

Input will consist of a series of lines each containing a value for N and k asintegers. 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 ofstudents in the order in which they leave the queue. Students are ordered according to theirposition in the at the start of the day. AlI numbers must be right justified in a field ofwidth 3.

65

Page 119: Programozási Versenyfeladatok - Programing Contests

Samples:

I INPUT I OUTPUT

5 3

O Ol 3 5 2

Name: Amazing

Files:programinputoutput

g.pasg.inpg.out

Task:

RUGB92 7

One of the apparently intelligent tricks that enthusiastic psychologists persuade miceto perform is solving a maze. There is still some controversy as to the exact strategiesemployed by the mice when engaged in such a task, but it has been claimed that the animaIkeepers eavesdropping on conversations between the mice have heard them say things like "1have 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 suchmazes would be a good test of the 'intelligence' built into such machines by theirdesigners. However, to their chagrin, the first contest was won by a robot that placed asensor on the right hand wall of the maze and sped through the maze maintaining contact withthe right hand wall at alI times. This led to a change in the design of the mazes, and alsoto interest in the behavior of such robots. To test this behavior the mazes were modified tobe come closed boxes with internal walls. The robot was placed in the south west corner andset off pointing east. The robot then moved through the maze keeping a wall on its right atalI times. If it cannot proceed it will turn left until it can proceed. AlI turns are exactright angles. The robot stops when it returns to the starting square. The mazes were alwaysset up so that the robot could move to at least one other square before returning. Theresearchers then determined how many squares were not visi ted, and how many were visi tedonce, twice, thrice and four times. AlI square is visited if a robot moves into and out ofit. Thus for the following maze, the values (in order) are: 2, 3, 5, 1, O .

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

values.

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

66

Page 120: Programozási Versenyfeladatok - Programing Contests

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

Samples:

INPUT OUTPUT

3 5 2 351 O010100101000000O O

Name: Ali Squares RUGB92 8

Files:programinputoutput

h.pash.inph.out

Task:

Geometrically, any square has a unique, well-defined center point. On a grid this ison true if the sides of the square are an add number of points long. Since any add numb canbe written in the form 2k+1, we can characterize any such square by specifying that is wecan say that a square whose sides are of length 2k+1 has size k . Now define patt ern ofsquares as follaws.

1. The largest square is of size k (that is sides are of length 2k+1) and is centeredin 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, the1<k<512.

3. All squares of size k > 1 have a square of size k div. 2 centred on each of theircorners. (Div implies integer division, thus 9 div 2 = 4).

4. The top left corner of the screen has coordinates (O, O), the bottom right hascoordinates (2048, 2048).

Hence, given a value of k, we can draw a unique pattern of squares according to theabove 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 thatsquare). Thus if the size of the largest square is given as 15, then the follawing patternwould be produced.

67

Page 121: Programozási Versenyfeladatok - Programing Contests

/,}, '..~

Write a program that will read in a value of k and the coordinates of a point, and wdetermine how many squares surround the point.

Input will consist of a series of lines. Each line will consist of a value of k andthe 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 linewill consist of the number of squares containing the specified point, right justified in afield of width 3.

Samples:

941

Name: SpreadsheetCalculator

ACMF92 - 1

Files:programinputoutput

a.pasa.inpa.out

Task:

A spreadsheet is a rectangular array of cells. Cells contain data or expressions thatcan be evaluated to obtain data. A 'simple' spreadsheet is one in which data are integersand expressions are mixed sums and differences of integers and cell references. For anyexpression, if each cell that is referenced contains an integer, then the express ion can be

68

Page 122: Programozási Versenyfeladatok - Programing Contests

replaced by the integer to which the express ion evaluates. You are to write a program whichevaluates simple spreadsheets.

InputInput 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 morethan 20 rows or 10 columns. Rows are labeled by capital letters A through T. Columns arelabeled by decimal digits O through 9. Therefore, the cell in the first row and firstcolumn is referenced as AO; the cell in the twentieth row and fifth column is referenced asT4.

Following the specification of the number of rows and columns is one line of data foreach 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 signedinteger value or an express ion involving unsigned integer constants, cell references, andthe operators + (addition) and (subtraction). If a cell initially contains a signedinteger, the corresponding input line will begin with an optional minus sign followed byone or more decimal digits. If a cell initially contains an expression, its input line willcontain one or more cell references or unsigned integer constants separated from each otherby + and - signs. Such a line must begin with a cell reference. No expression contains morethan 75 characters. No line of input contains leading blanks. No express ion contains anyembedded blanks. However, any line may contain trailing blanks.

The end of the sequence of spreadsheets is marked by a line specifying O rows and Ocolumns.

OutputFor 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 andcolumns 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 eachexpression; values in cells are always less than 10000 in absolute value. Sinceexpressions may re ference cells that themselves contain expressions, the order in whichcells 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 inrow-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:programinputoutput

b.pasb.inpb.out

Task:

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

69

Page 123: Programozási Versenyfeladatok - Programing Contests

5 ft.

(12,16)(8.16)

13.42 ft.

(8.11)

'1.18ft(24.10)

(13,8)

For various reasons it is desirable to minimize the length of cable used. Your problem isto determine how the computers should be connected into such a chain to minimize the totalamount of cable needed. In the installation being constructed, the cabling will run beneaththe floor, so the amount of cable used to join 2 adjacent computers on the network will beequal to the distance between the computers plus 16 additional feet of cab1e to connectfrom 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, andthe 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)

InputThe 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. Eachnetwork has at least 2 and at most 8 computers. A va1ue of O for the number of computersindicates the end of input. After the initial line in a data set specifying the number ofcomputers in a network, each additional line in the data set will give the coordinates of acomputer in the network. These coordinates will be integers in the range O to 150. No twocomputers are at identical locations and each computer will be listed once.

OutputThe 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 ofcable to be cut to connect each adjacent pair of computers in the network. The final lineshould be a sentence indicating the total amount of cable used. In listing the lengths ofcab1e to be cut, traverse the network from one end to the other. (It makes no difference atwhich end you start.) Use a format similar to the one shown in the sample output, with a

70

Page 124: Programozási Versenyfeladatok - Programing Contests

line of asterisks separating output for different networksprinted to 2 decimal places.

and with distances in feet

Samples:

INPUT OUTPUT

6 Network \#15 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 \#211 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 \#3132 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 DirectionFinder

ACMF92 3

Files:programinputoutput

c.pasc.inpC.out

Task:

A boat with a directional antenna can determine its present position with the help ofreadings from local beacons. Each beacon is located at a known position and emits a uniquesignal. When a boat detects a signal, it rotates its antenna until the signal is at maximalstrength. This gives a relative bearing to the posi tion of the beacon. Given a previousbeacon reading (the time, the relative bearing, and the position of the beacon), a newbeacon reading is usually sufficient to determine the boat's present position. You are towrite 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 rectangularcoordinate system. The positive x-axis points east; the positive y-axis points north. Thecourse is the direction of travel of the boat and is measured in degrees clockwise fromnorth. That is, north is 0i, east is 90i, south is 180i, and west is 270i The relativebearingboat's

of a beacon is given in degrees clockwise relative to the course of the boat. Abearing ofantenna cannot indicate on which side the beacon is located. A relative

90i means that the beacon is toward 90i or 270i.

Input

71

Page 125: Programozási Versenyfeladatok - Programing Contests

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 they-coordinate of its position. These fields are single-space separated.

Coming after the lines of beacon information is an integer specifying a number ofboat scenarios to follow. A boat scenario consists of three lines, one for velocity and twofor beacon readings.

Data on input linecourse speedtime#l name#l angle#l

Meaning of datathe boat's course, the speed at which it is travelingtime of first beacon reading, name of first beacon, relative

bearing of first beacontime of second reading, name of second beacon, relative

bearing of second beacontime#2 name#2 angle#2

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 thereading (an integer), the name of the beacon, and the angle of the reading as measured fromthe boat's course. These 3 fields have single space separators. The third line gives thesecond beacon reading. The time for that reading will always be at least as large as thetime for the first reading.

OutputFor 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) ofthe boat as of the time of the second beacon reading. If it is impossible to determine theposition of the boat, the message should say 'Position cannot be determined.'

Name: Moth Eradication ACMF92 4

Files:programinputoutput

d.pasd.inpd.out

Task:

Entomologists in the Northeast have set out traps to determine the influx of Jollietmoths into the area. They plan to study eradication programs that have some potential tocontrol the spread of the moth population. The study calls for organizing the traps in whichmoths have been caught into compact regions, which will then be used to test eacheradication program. A reg ion is defined as the polygon with the minimum length perimeterthat 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

Page 126: Programozási Versenyfeladatok - Programing Contests

You must write a program that can take as input the locations of traps in aand output the locations of traps that lie on the perimeter of the region as weillength of the perimeter.

regionas the

InputThe 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 ofthe 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 regionwith O traps.

OutputOutput 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.)A listing of a11 the points that appear on the perimeter of the

The points must be identified in the standard form '(x-coordinate)' rounded to a single decimal place. The startingthis listing is irrelevant, but the listing must be oriented

and begin and end with the same point. Forwhich describes the minimum length perimeter isany order

Next 1ine(s):region.coordinate,y-point forclockwisecollinear points,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 outputsample input is shown on the reverse.

for the

Samples:

INPUT

Region #1(1.0,2.0)-(4.0,10.0)-(5.0,12.3)-(1.0,2.0)Perimeter length = 22.10

OUTPUT

3

1 24 105 12.3

73

Page 127: Programozási Versenyfeladatok - Programing Contests

Region #2:(O.O, O.O)- (3.0,4.5) - (6.0,2.1) - (2.O, -3.2)-(0.0,0.0)

6O O

1 13.1 1.33 4.56 2.12 -3.27

Perimeter length 19.66

Region #3:(O.O,O.O)- (2.0,2. O)- (4.0,1. 5) - (5.O, O.0)-(2.5,-1.5)-(0.0,0. O)

Perimeter length = 12.521 0.55 O4 1.53 -0.22.5 -1.5O O2 2O

Name: Department ofRedundancyDepartment

5ACMF92

Files:programinputoutput

e.pase.inpe.out

Task:

When designing tables for a relational database, a functiona1 dependency (FO) is usedto express the relationship between the di fferent fields. A functional dependency isconcerned with the relationship of values of one set of fie1ds to those of another set offields. The notation X->Y is used to denote that when supplied va1ues to the field (s) inset X, the assigned value for each field in set Y can be determined. For example, if adatabase table is to contain fie1ds for the social security number (S), name(A), and phone (P) and each person has been assigned a unique value for S,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. AnFO is redundant if it can be derived using other FOs in the group. For example, if the

(N) ,

theaddressS field

group contains the FOs A->B, B->C, and A->C, then the third FO is redundant since the fieldset 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.

InputThe 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 thatgroup. A group with zero FOs indicates the end of the input. Each FO in the group appearson a separate line containing two non- empty lists of field names separated by thecharacters - and >. The lists of fie1d names contain only uppercase alphabetic characters.Functiona1 dependency lines contain no b1anks or tabs. There are no tri vially redundantFOs (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.

OutputFor 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 theindicated FO is redundant. If more than one sequence of FOs can be used to show another FO

74

Page 128: Programozási Versenyfeladatok - Programing Contests

is redundant,sequence. Bachof FDs contains

any such sequence is acceptable,FD in an acceptable proof sequence

no redundancy, display No redundant

even if it is not the shortest proofhowever, be necessary. If a groupmust,

FDs.

Name: Othello ACMF92 6

Files:programinputoutput

f.pasf.inpf.out

Task:

Othello is a game played by two people on an 8 x 8 board, using disks that are whiteon one side and black on the other. One player places disks with the white side up and theother player places disks with the black side up. The players alternate placing one disk onan unoccupied space on the board. In placing a disk, the player must bracket at least oneof 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 theline. When a move is made, alI the disks that were bracketed are changed to the color ofthe player making the move. (It is possible that disks will be bracketed across more thanone line in a single move.)

Write a program to read a series of Othello games. The first line of the input is thenumber of games to be processed. Bach game consists of a board configuration followed by alist of commands. The board configuration consists of 9 lines. The first 8 specify thecurrent state of the board. Bach of these 8 lines contains 8 characters, and each of thesecharacters 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. Youmay assume that the data is legally formatted.

The commands are to list alI possible moves for the current player, make aquit the current game. There is one command per line with no blanks in the input.are formatted as follows:

move, orCommands

List aLl, possible moves for the current player. The command is an 'L' in the firstcolumn of the line. The program should go through the board and print alI legal moves forthe current player in the format (x,y) where x represents the row of the legal move and yrepresents 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 legalmove in row number j if j is greater than iand2) if there is more than one legal move in row number i, the moves will beprinted in ascending order based on column number.

AlI legal moves should be put on one line. If there is noimpossible for the current player to bracket any pieces,message 'No legal move.'

Make a move. The command is an 'M' in the first column of the line, followed by 2digits in the second and third column of the line. The digits are the row and the column ofthe space to place the piece of the current player's color, unless the current player hasno legal move. If the current player has no legal move, the current player is first changedto the other player and the move will be the move of the new current player. You may assumethat the move is then legal. You should record the changes to the board, including addingthe new piece and changing the color of alI bracketed pieces. At the end of the move, print

thelegal move because it isprogram should print the

75

Page 129: Programozási Versenyfeladatok - Programing Contests

the number of pieces of each color on the board in the format 'Black - xx White - yy' wherexx is the number of black pieces on the board and yy is the number of white pieces on theboard. 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. Atthis point, print the final board configuration using the same format as was used in theinput. This terminates input for the current game.

You may assume that the commands will be syntactically correct. Put one blank linebetween output from separate games and no blank lines anywhere else in the output.

Name: Urban Elevations ACMF92 - 7

Files:programinputoutput

g.pasg.inpg.aut

Task:

An elevation of a collection of buildings is an orthogonal projection of thebuildings onto a vertical plane. An external elevation of a city would show the skyline andthe faces of the 'visible' buildings of the city as viewed from outside the city from acertain direction. A southern elevation shows no sides; it shows the perfectly rectangularfaces of buildings or parts of faces of buildings not obstructed on the south by tallerbuildings. For this problem, you must wri te a program that determines which buildings of acity are visible in a southern elevation.

For simplicity, assume aLL the buildings for the elevation are perfect rectangularsolids, 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 onknowing the positions and heights of each city building. That data can be illustrated by amap of the city as in the diagram on the left below. The southern elevation for that cityis illustrated in the diagram on the right.

19 801 LJ ~50 35

~ o 4

30 1 ~III 25

[;]14

501 D "90 110lS 80 I [;J ~ 30 5 9 4 3 10 2

InputInput 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 city (a non-negati veinteger less than 101). Each subsequent line of a map contains data for a single building N5 real numbers separated by spaces in the following order:

x-coordinate of the southwest cornery-coordinate of the southwest cornerwidth 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-axispoints east and the positive y-axis points north. Assume that aII input for each map

76

Page 130: Programozási Versenyfeladatok - Programing Contests

corresponds to a legitimate map (the number of buildings is the same as the number ofsubsequent lines of input for the map; no two buildings in a single map overlap). Input isterminated by the number O representing a map with no buildings.

OutputBuildings 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 tothe next line, and building #n to the nth line of building data for that map. (Buildings onsubsequent maps also begin their numbering wi th 1.) For each map, output begins wi th lineidentifying the map (map #1, map #2, etc.) On the next line the numbers of the visiblebuildings 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 southwestcorner of building n is west of the southwest corner of building m , then number n isprinted before number m. If building n and building m have the same x-coordinate for theirsouthwest corners and if building n is south of building m, then the number n is printedbefore the number m. For this program, a building is considered visible whenever the partof its southern face that appears in the elevation has strictly positi ve area. One blankline must separate output from consecutive input records

Samples:

INPUT OUTPUT

160 O 30 60 30 map #1125 O 32 28 60 5 9 4 3 10 2 1 1495 O 27 28 4070 35 19 55 90O O 60 35 80O 40 29 20 6035 40 25 45 80O 67 25 20 50O 92 90 2O 8O95 38 55 12 5095 60 60 13 3095 80 45 25 50165 65 15 15 25165 85 10 15 35O

Name: Urban Elevation KLTE93 - 1

Files:programinputoutput

urban.pasurban.inpurban.out

See ACMF92-7

Name: Moth Eradiction KLTE93 - 2

Files:programinputoutput

moth.pasmoth.inpmoth.out

See ACMF92-4

77

Page 131: Programozási Versenyfeladatok - Programing Contests

Name: Getting in Line KLTE93 - 3

Files:programinputoutput

line.pasline.inpline.out

See ACMF92-2

Name: Fibonacci Loops KLTE93 - 4

Files:programinputoutput

loops.pasloops.inploops.out

Task:

A Fibonacci loop is a set of three numeric vectors that has a particular property. Itis 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 numberof occurrences of i in the other two vectors. In this example, the '6' in Fl indicates atotal of 6 zeroes in F2 and F3. Similarly, the '9' in F3 indicates a total of 9 ones in Fland F2. Sach vector in the set describes the union of the other two vectors. Wri te aprogram to read in pairs of vectors. The numbers within the vector pairs will be separatedfrom each other by one or more spaces. The value of any number in any vector will not exceedthe number of elements in that vector. A vector will be contained on a single line, lessthan 80 characters in length. The input will be terminated by end-of file. If the pair ofvectors 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 Fland F3, and F3 describes Fl and F2. Print the vector sets in formatted columns similar tothe 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

Page 132: Programozási Versenyfeladatok - Programing Contests

Samples:

INPUT OUTPUT

6 6 2 2 O 2 O 2 O O 6 6 2 20202007 3 5 1 O 1 2 1 O O 7 3 5 1 O 1 2 1007 6 2 1 O 1 1 1 1 7 3 5 1 O 1 2 1005 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 13 O 3 2 2 5 8 1 1 O O 2 2 12 O 4 4 O 3 8 3 O O 1 1 1 1

Invalid solution.

673001 1107 6 2 1 O i 1 101Vectors are of different sizes.

3 2 3 2 22 O 4 4 O3 O 3 2 2A valid Fibonacci loop.

Name: Fractured Fraction KLTE93 - 5

Files:programinputoutput

fract.pasfract.inpfract.out

Task:

A fractured fraction is a special form that includes a continued fraction in whichonly single-digit, positive integers appear and no digit (except 1) appears more than once.Examples of fractured fractions are:

7125

1 929

11 '1+--15+-4

13+--14+-2

Develop a program that determines whether a given standard fraction can be representedas a fractured fraction. If a fractured fraction representation exists, a pretty-printedversion 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

Page 133: Programozási Versenyfeladatok - Programing Contests

-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 fractionswhich reduce to single digit integers are to be considered valid fractured fractions as arefractions such as one-hal f, one-third, etc.

InputThe input data for this program consists of a series of fractions, one perdata line in the following format:

numerator denominatorwhere both input values are integers separated by at least one space. The input will

be terminated by end-of file.

OutputThe 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 followingerror message:

NO FRACTURED FORM: numerator / denominator$ - Issued when the input fra ct ion cannotbe represented as a fractured fraction.

You may assume that no fractured fra ct ion will contain a line in excess of 80characters in length. The results of processing each input fraction should be separated bytwo blank lines in your output.

Samples:

INPUT OUTPUT

71 25 15 O 2 + ---------3 5 112 3 1 + -----

3 12 18 -ll 5 + ---

21814 6833 4

NO FRACTURED FORM: 5/0

1-----------

11 + -------

11 + ---

2

NO FRACTURED FORM: 8 / -11

NO FRACTURED FORM: 21814 / 6833

80

Page 134: Programozási Versenyfeladatok - Programing Contests

Name: Wordlist KLTE93 - 6

Files:programinputoutput

word.pasword.inpword.out

Task:

YourThe Mumble Puzzle Company produces word puzzlesboss has decided he wants all possible words to

for newspapers acrosshave a number. To be

the country.sure of not

missing a word, and because you have a computer to do all the work anyway, he wants allstrings of one to twenty lower-case letters included. The words are ordered first by length,then alphabetically. The list looks like this:

1 a2 b

26 z27 aa28 ab

310012476284 a10ngword

Your job is to produce a program that will translate between the position numbers andthe 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 consistsonly of digi ts (O-9). A word consists only of lower-case 1etters (a-z). No word will belonger than 20 letters. Your program must produce the line in the word list that containsthe 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 commasat thousands, millions, and so on.

Samples:

INPUT OUTPUT

psychopathological 19, 011, 949,514, 367,212,753, 990,730 psychopathological1347896067682984 1,347,896,067,682,984 information751174307943 751,174,307,943 computingfun 4,616 funzzzzzzzzzzzzzzzzzzzz 20,725,274,851,017,785,518,433,805,270 zzzzzzzzzzzzzzzzzzzz

81