boxes with souvenirs - ntnutoi.csie.ntnu.edu.tw/file/20160120090541.pdf · boxes with souvenirs the...

17
1/3 International Olympiad in Informatics 2015 26th July- 2nd August 2015 Almaty, Kazakhstan Day 1 boxes Language: en-ISC Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony, each team was supposed to receive a box with a souvenir from the host. However, all volunteers are so fascinated by the ceremony that they completely forgot about the souvenirs. The only person who remembers about the souvenirs is Aman. He is an enthusiastic volunteer and he wants the IOI to be perfect, so he wants to deliver all the souvenirs in the least amount of time. The venue of the opening ceremony is a circle divided into identical sections. The sections around the circle are numbered consecutively from to . That is, for , sections and are adjacent, and also sections and are adjacent. There are teams at the venue. Each team is sitting in one of the sections. Each section may contain arbitrarily many teams. Some sections may even be empty. There are identical souvenirs. Initially, both Aman and all of the souvenirs are in section . Aman should give one souvenir to each team, and after delivering the last souvenir he must return to section . Note that some teams may be sitting in section 0. At any moment, Aman can only carry at most souvenirs. Aman must pick up souvenirs in section , and this takes him no time. Each souvenir must be carried until it is delivered to one of the teams. Whenever Aman carries one or more souvenirs and reaches a section with a team that has not received a souvenir yet, he may give that team one of the souvenirs he carries. This also happens instantly. The only thing that takes time is movement. Aman can move around the circular venue in both directions. Moving to an adjacent section (either clockwise or counterclockwise) takes him exactly one second, regardless of how many souvenirs he carries. Your task is to find the smallest number of seconds Aman needs to deliver all souvenirs and then return to his initial position. Example In this example we have teams, Aman’s carrying capacity is , and the number of sections is . The teams are located in sections 1, 2, and 5.

Upload: others

Post on 01-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/3

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay1

boxesLanguage:en-ISC

BoxeswithsouvenirsThelastactoftheIOI2015openingceremonyisinprogress.Duringtheopeningceremony,eachteamwassupposedtoreceiveaboxwithasouvenirfromthehost.However,allvolunteersaresofascinatedbytheceremonythattheycompletelyforgotaboutthesouvenirs.TheonlypersonwhoremembersaboutthesouvenirsisAman.HeisanenthusiasticvolunteerandhewantstheIOItobeperfect,sohewantstodeliverallthesouvenirsintheleastamountoftime.

Thevenueoftheopeningceremonyisacircledividedinto identicalsections.Thesectionsaroundthecirclearenumberedconsecutivelyfromto .Thatis,for ,sections and areadjacent,andalsosections and areadjacent.Thereare teamsatthevenue.Eachteamissittinginoneofthesections.Eachsectionmaycontainarbitrarilymanyteams.Somesectionsmayevenbeempty.

Thereare identicalsouvenirs.Initially,bothAmanandallofthesouvenirsareinsection .Amanshouldgiveonesouvenirtoeachteam,andafterdeliveringthelastsouvenirhemustreturntosection .Notethatsometeamsmaybesittinginsection0.

Atanymoment,Amancanonlycarryatmost souvenirs.Amanmustpickupsouvenirsinsection ,andthistakeshimnotime.Eachsouvenirmustbecarrieduntilitisdeliveredtooneoftheteams.WheneverAmancarriesoneormoresouvenirsandreachesasectionwithateamthathasnotreceivedasouveniryet,hemaygivethatteamoneofthesouvenirshecarries.Thisalsohappensinstantly.Theonlythingthattakestimeismovement.Amancanmovearoundthecircularvenueinbothdirections.Movingtoanadjacentsection(eitherclockwiseorcounterclockwise)takeshimexactlyonesecond,regardlessofhowmanysouvenirshecarries.

YourtaskistofindthesmallestnumberofsecondsAmanneedstodeliverallsouvenirsandthenreturntohisinitialposition.

ExampleInthisexamplewehave teams,Aman’scarryingcapacityis ,andthenumberofsectionsis .Theteamsarelocatedinsections1,2,and5.

Page 2: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/3

Oneoftheoptimalsolutionsisshowninthepictureabove.InhisfirsttripAmantakestwosouvenirs,deliversonetotheteaminsection2,thentheothertotheteaminsection5,andfinallyhereturnstosection0.Thistriptakes8seconds.InhissecondtripAmanbringstheremainingsouvenirtotheteaminsection1andthenreturnstosection0.Heneedsanother2secondstodothis.Thus,thetotaltimeis10seconds.

TaskYouaregiven , , ,andthepositionsofallteams.ComputethesmallestnumberofsecondsAmanneedstodeliverallthesouvenirsandtoreturntosection .Youneedtoimplementthefunctiondelivery:

delivery(N,K,L,positions) —Thisfunctionwillbecalledbythegraderexactlyonce.

N:thenumberofteams.K:themaximumnumberofsouvenirsAmancancarryatthesametime.L:thenumberofsectionsinthevenueoftheopeningceremony.

positions:anarrayoflength .positions[0],...,positions[N-1]givethesectionnumberofallteams.Theelementsofpositionsareinnon-decreasingorder.ThefunctionshouldreturnthesmallestnumberofsecondsinwhichAmancancompletehistask.

Subtasks

subtask points1 102 103 154 155 20

Page 3: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

3/3

6 30subtask points

SamplegraderThesamplegraderreadstheinputinthefollowingformat:

line1:NKLline2:positions[0]…positions[N-1]

Thesamplegraderprintsthereturnvalueofdelivery.

Page 4: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/3

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay1

scalesLanguage:en-ISC

ScalesAminahassixcoins,numberedfrom to .Sheknowsthatthecoinsallhavedifferentweights.Shewouldliketoorderthemaccordingtotheirweight.Forthispurposeshehasdevelopedanewkindofbalancescale.

Atraditionalbalancescalehastwopans.Tousesuchascale,youplaceacoinintoeachpanandthescalewilldeterminewhichcoinisheavier.

Amina’snewscaleismorecomplex.Ithasfourpans,labeled , , ,and .Thescalehasfourdifferentsettings,eachofwhichanswersadifferentquestionregardingthecoins.Tousethescale,Aminamustplaceexactlyonecoinintoeachofthepans , ,and .Additionally,inthefourthsettingshemustalsoplaceexactlyonecoinintopan .

Thefoursettingswillinstructthescaletoanswerthefollowingfourquestions:

1. Whichofthecoinsinpans , ,and istheheaviest?2. Whichofthecoinsinpans , ,and isthelightest?3. Whichofthecoinsinpans , ,and isthemedian?(Thisisthecointhatisneitherthe

heaviestnorthelightestofthethree.)4. Amongthecoinsinpans , ,and ,consideronlythecoinsthatareheavierthanthecoinon

pan .Ifthereareanysuchcoins,whichofthesecoinsisthelightest?Otherwise,iftherearenosuchcoins,whichofthecoinsinpans , ,and isthelightest?

TaskWriteaprogramthatwillorderAmina’ssixcoinsaccordingtotheirweight.TheprogramcanqueryAmina’sscaletocompareweightsofcoins.Yourprogramwillbegivenseveraltestcasestosolve,eachcorrespondingtoanewsetofsixcoins.

YourprogramshouldimplementthefunctionsinitandorderCoins.Duringeachrunofyourprogram,thegraderwillfirstcallinitexactlyonce.Thisgivesyouthenumberoftestcasesandallowsyoutoinitializeanyvariables.ThegraderwillthencallorderCoins()oncepertestcase.

init(T)T:Thenumberoftestcasesyourprogramwillhavetosolveduringthisrun.Tisanintegerfromtherange .

Thisfunctionhasnoreturnvalue.

orderCoins()Thisfunctioniscalledexactlyoncepertestcase.

ThefunctionshoulddeterminethecorrectorderofAmina’scoinsbycallingthegrader

Page 5: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/3

functionsgetHeaviest(),getLightest(),getMedian(),and/orgetNextLightest().Oncethefunctionknowsthecorrectorder,itshouldreportitbycallingthegraderfunctionanswer().Aftercallinganswer(),thefunctionorderCoins()shouldreturn.Ithasnoreturnvalue.

Youmayusethefollowinggraderfunctionsinyourprogram:

answer(W)—yourprogramshouldusethisfunctiontoreporttheanswerthatithasfound.

W:Anarrayoflength6containingthecorrectorderofcoins.W[0]throughW[5]shouldbethecoinnumbers(i.e.,numbersfrom to )inorderfromthelightesttotheheaviestcoin.

YourprogramshouldonlycallthisfunctionfromorderCoins(),oncepertestcase.Thisfunctionhasnoreturnvalue.

getHeaviest(A,B,C),getLightest(A,B,C),getMedian(A,B,C) —thesecorrespondtosettings1,2and3respectivelyforAmina’sscale.

A,B,C:Thecoinsthatareputinpans , ,and ,respectively.A,B,andCshouldbethreedistinctintegers,eachbetween and inclusive.

EachfunctionreturnsoneofthenumbersA,B,andC:thenumberoftheappropriatecoin.Forexample,getHeaviest(A,B,C)returnsthenumberoftheheaviestofthethreegivencoins.

getNextLightest(A,B,C,D) —thiscorrespondstosetting4forAmina’sscale

A,B,C,D:Thecoinsthatareputinpans , , ,and ,respectively.A,B,C,andDshouldbefourdistinctintegers,eachbetween and inclusive.

ThefunctionreturnsoneofthenumbersA,B,andC:thenumberofthecoinselectedbythescaleasdescribedaboveforsetting4.Thatis,thereturnedcoinisthelightestamongstthosecoinsonpans , ,and thatareheavierthanthecoininpan ;or,ifnoneofthemisheavierthanthecoinonpan ,thereturnedcoinissimplythelightestofallthreecoinsonpans , ,and .

ScoringTherearenosubtasksinthisproblem.Instead,yourscorewillbebasedonhowmanyweighings(totalnumberofcallstograderfunctionsgetLightest(),getHeaviest(),getMedian()and/orgetNextLightest())yourprogrammakes.

Yourprogramwillberunmultipletimeswithmultipletestcasesineachrun.Let bethenumberofrunsofyourprogram.Thisnumberisfixedbythetestdata.Ifyourprogramdoesnotorderthecoinscorrectlyinanytestcaseofanyrun,itwillget0points.Otherwise,therunsarescoredindividuallyasfollows.

Let bethesmallestnumbersuchthatitispossibletosortanysequenceofsixcoinsusingweighingsonAmina’sscale.Tomakethetaskmorechallenging,wedonotrevealthevalueof

Page 6: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

3/3

here.

Supposethelargestnumberofweighingsamongstalltestcasesofallrunsis forsomeinteger.Then,considerasinglerunofyourprogram.Letthelargestnumberofweighingsamongstall

testcasesinthisrunbe forsomenon-negativeinteger .(Ifyouusefewerthan weighingsforeverytestcase,then .)Then,thescoreforthisrunwillbe ,roundeddownto

twodigitsafterthedecimalpoint.

Inparticular,ifyourprogrammakesatmost weighingsineachtestcaseofeveryrun,youwillget100points.

ExampleSupposethecoinsareordered fromthelightesttotheheaviest.

Functioncall Returns ExplanationgetMedian(4,5,6) 6 Coin isthemedianamongcoins , ,and .getHeaviest(3,1,2) 1 Coin istheheaviestamongcoins , ,and .getNextLightest(2,3,4,5) 3 Coins , ,and arealllighterthancoin ,sothelightestamong

them( )isreturned.getNextLightest(1,6,3,4) 6 Coins and arebothheavierthancoin .Amongcoins and ,

coin isthelightestone.getHeaviest(3,5,6) 5 Coin istheheaviestamongcoins , and .getMedian(1,5,6) 1 Coin isthemedianamongcoins , and .getMedian(2,4,6) 6 Coin isthemedianamongcoins , and .answer([3,4,6,2,1,5]) Theprogramfoundtherightanswerforthistestcase.

SamplegraderThesamplegraderreadsinputinthefollowingformat:

line : —-thenumberoftestcases

eachofthelinesfrom to :asequenceof distinctnumbersfrom to :theorderofthecoinsfromthelightesttotheheaviest.

Forinstance,aninputthatconsistsoftwotestcaseswherethecoinsareordered andlooksasfollows:

2123456346215

Thesamplegraderprintsthearraythatwaspassedasaparametertotheanswer()function.

Page 7: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/2

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay1

teamsLanguage:en-ISC

TeamsThereisaclassof students,numbered through .Everydaytheteacheroftheclasshassomeprojectsforthestudents.Eachprojecthastobecompletedbyateamofstudentswithinthesameday.Theprojectsmayhavevariousdifficulty.Foreachproject,theteacherknowstheexactsizeofateamthatshouldworkonit.

Differentstudentsmaypreferdifferentteamsizes.Moreprecisely,student canonlybeassignedtoateamofsizebetween and inclusive.Oneachday,astudentmaybeassignedtoatmostoneteam.Somestudentsmightnotbeassignedtoanyteams.Eachteamwillworkonasingleproject.

Theteacherhasalreadychosentheprojectsforeachofthenext days.Foreachofthesedays,determinewhetheritispossibletoassignstudentstoteamssothatthereisoneteamworkingoneachproject.

ExampleSupposethereare studentsand days.Thestudents’constraintsonteamsizesaregiveninthetablebelow.

student 0 1 2 31 2 2 22 3 3 4

Onthefirstdaythereare projects.Therequiredteamsizesare and .Thesetwoteamscanbeformedbyassigningstudent0toateamofsize1andtheremainingthreestudentstoateamofsize3.

Ontheseconddaythereare projectsagain,butthistimetherequiredteamsizesareand .Inthiscaseitisnotpossibletoformtheteams,asthereisonlyonestudent

whocanbeinateamofsize1.

TaskYouaregiventhedescriptionofallstudents: , ,and ,aswellasasequenceof questions—oneabouteachday.Eachquestionconsistsofthenumber ofprojectsonthatdayandasequenceoflength containingtherequiredteamsizes.Foreachquestion,yourprogrammustreturn

whetheritispossibletoformalltheteams.

Youneedtoimplementthefunctionsinitandcan:init(N,A,B)—Thegraderwillcallthisfunctionfirstandexactlyonce.

N:thenumberofstudents.

Page 8: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/2

A:anarrayoflengthN:A[i]istheminimumteamsizeforstudent .B:anarrayoflengthN:B[i]isthemaximumteamsizeforstudent .Thefunctionhasnoreturnvalue.

Youmayassumethat A[i] B[i] Nforeach N .

can(M,K)—Aftercallinginitonce,thegraderwillcallthisfunction timesinarow,onceforeachday.

M:thenumberofprojectsforthisday.K:anarrayoflengthMcontainingtherequiredteamsizeforeachoftheseprojects.Thefunctionshouldreturn1ifitispossibletoformalltherequiredteamsand0otherwise.

Youmayassumethat M ,andthatforeach M wehave K[i].NotethatthesumofallK[i]mayexceed .

SubtasksLetusdenoteby thesumofvaluesofMinallcallstocan(M,K).

subtask points AdditionalConstraints1 21 none2 13 none3 434 23

SamplegraderThesamplegraderreadstheinputinthefollowingformat:

line1:Nlines2,…,N+1:A[i]B[i]lineN+2:QlinesN+3,…,N+Q+2:MK[0]K[1]…K[M-1]

Foreachquestion,thesamplegraderprintsthereturnvalueofcan.

Page 9: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/3

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay2

horsesLanguage:en-ISC

HorsesMansurlovestobreedhorses,justlikehisancientancestorsdid.HenowhasthelargestherdinKazakhstan.Butthiswasnotalwaysthecase. yearsago,Mansurwasjustadzhigit(Kazakhforayoungman)andheonlyhadasinglehorse.Hedreamedtomakealotofmoneyandtofinallybecomeabai(Kazakhforaveryrichperson).

Letusnumbertheyearsfrom to inchronologicalorder(i.e.,year isthemostrecentone).Theweatherofeachyearinfluencedthegrowthoftheherd.Foreachyear ,Mansurremembersapositiveintegergrowthcoefficient .Ifyoustartedyear with horses,youendedtheyearwith horsesinyourherd.

Horsescouldonlybesoldattheendofayear.Foreachyear ,Mansurremembersapositiveinteger:thepriceforwhichhecouldsellahorseattheendofyear .Aftereachyear,itwaspossibleto

sellarbitrarilymanyhorses,eachatthesameprice .

Mansurwonderswhatisthelargestamountofmoneyhecouldhavenowifhehadchosenthebestmomentstosellhishorsesduringthe years.YouhavethehonorofbeingaguestonMansur’stoi(Kazakhforholiday),andheaskedyoutoanswerthisquestion.

Mansur’smemoryimprovesthroughouttheevening,andsohemakesasequenceof updates.Eachupdatewillchangeeitheroneofthevalues oroneofthevalues .Aftereachupdateheagainasksyouthelargestamountofmoneyhecouldhaveearnedbysellinghishorses.Mansur’supdatesarecumulative:eachofyouranswersshouldtakeintoaccountallofthepreviousupdates.Notethatasingle or maybeupdatedmultipletimes.

TheactualanswerstoMansur’squestionscanbehuge.Inordertoavoidworkingwithlargenumbers,youareonlyrequiredtoreporttheanswersmodulo .

ExampleSupposethatthereare years,withthefollowinginformation:

0 1 2

X 2 1 3

Y 3 4 1

Fortheseinitialvalues,Mansurcanearnthemostifhesellsbothhishorsesattheendofyear1.Theentireprocesswilllookasfollows:

Initially,Mansurhas1horse.

Afteryear0hewillhave horses.

Page 10: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/3

Afteryear1hewillhave horses.

Hecannowsellthosetwohorses.Thetotalprofitwillbe .

Then,supposethatthereis update:changing to .

Aftertheupdatewewillhave:

0 1 2

X 2 1 3

Y 3 2 1

Inthiscase,oneoftheoptimalsolutionsistosellonehorseafteryear0andthenthreehorsesafteryear2.Theentireprocesswilllookasfollows:

Initially,Mansurhas1horse.

Afteryear0hewillhave horses.

Hecannowselloneofthosehorsesfor ,andhaveonehorseleft.

Afteryear1hewillhave horse.

Afteryear2hewillhave horses.

Hecannowsellthosethreehorsesfor .Thetotalamountofmoneyis .

TaskYouaregiven , , ,andthelistofupdates.Beforethefirstupdate,andaftereveryupdate,computethemaximalamountofmoneythatMansurcouldgetforhishorses,modulo .Youneedtoimplementthefunctionsinit,updateX,andupdateY.

init(N,X,Y)—Thegraderwillcallthisfunctionfirstandexactlyonce.N:thenumberofyears.X:anarrayoflength .For , givesthegrowthcoefficientforyear.

Y:anarrayoflength .For , givesthepriceofahorseafteryear.

NotethatbothXandYspecifytheinitialvaluesgivenbyMansur(beforeanyupdates).Afterinitterminates,thearraysXandYremainvalid,andyoumaymodifytheircontentsifyouwish.

ThefunctionshouldreturnthemaximalamountofmoneyMansurcouldgetfortheseinitialvaluesof and ,modulo .

updateX(pos,val)pos:anintegerfromtherange .

Page 11: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

3/3

val:thenewvaluefor pos .ThefunctionshouldreturnthemaximalamountofmoneyMansurcouldgetafterthisupdate,modulo .

updateY(pos,val)pos:anintegerfromtherange .

val:thenewvaluefor pos .ThefunctionshouldreturnthemaximalamountofmoneyMansurcouldgetafterthisupdate,modulo .

Youmayassumethatalltheinitial,aswellasupdatedvaluesof and arebetween andinclusive.

Aftercallinginit,thegraderwillcallupdateXandupdateYseveraltimes.ThetotalnumberofcallstoupdateXandupdateYwillbe .

Subtasks

subtask points additionalconstraints

1 17 ,

2 17 none

3 20 and forinitandupdateXcorrespondingly

4 23 none5 23 none

SamplegraderThesamplegraderreadstheinputfromthefilehorses.ininthefollowingformat:

line1:Nline2:X[0]…X[N-1]line3:Y[0]…Y[N-1]line4:Mlines5,…,M+4:threenumberstypeposval(type=1forupdateXandtype=2forupdateY).

ThesamplegraderprintsthereturnvalueofinitfollowedbythereturnvaluesofallcallstoupdateXandupdateY.

Page 12: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/3

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay2

sortingLanguage:en-ISC

SortingAizhanhasasequenceof integers .Thesequenceconsistsofdistinctnumbersfrom to .Sheistryingtosortthissequenceinascendingorderbyswappingsomepairsofelements.HerfriendErmekisalsogoingtoswapsomepairsofelements—notnecessarilyinahelpfulway.

ErmekandAizhanaregoingtomodifythesequenceinaseriesofrounds.Ineachround,firstErmekmakesaswapandthenAizhanmakesanotherswap.Moreprecisely,thepersonmakingaswapchoosestwovalidindicesandswapstheelementsatthoseindices.Notethatthetwoindicesdonothavetobedistinct.Iftheyareequal,thecurrentpersonswapsanelementwithitself,whichdoesnotchangethesequence.

AizhanknowsthatErmekdoesnotactuallycareaboutsortingthesequence .ShealsoknowstheexactindicesErmekisgoingtochoose.Ermekplanstotakepartin roundsofswapping.Wenumbertheseroundsfrom to .Foreach between and inclusive,Ermekwillchoosetheindices and inround .

Aizhanwantstosortthesequence .Beforeeachround,ifAizhanseesthatthesequenceisalreadysortedinascendingorder,shewillterminatetheentireprocess.Giventheoriginalsequence andtheindicesErmekisgoingtochoose,yourtaskistofindasequenceofswaps,whichAizhancanusetosortthesequence .Inaddition,insomesubtasksyouarerequiredtofindasequenceofswapsthatisasshortaspossible.Youmayassumethatitispossibletosortthesequence in orfewerrounds.

NotethatifAizhanseesthatthesequence issortedafterErmek’sswap,shecanchoosetoswaptwoequalindices(e.g., and ).Asaresultthesequence isalsosortedaftertheentireround,soAizhanreacheshergoal.Alsonotethatiftheinitialsequence isalreadysorted,theminimalnumberofroundsneededtosortitis .

Example1

Supposethat:

Theinitialsequenceis .

Ermekiswillingtomake swaps.

Thesequences and thatdescribetheindicesErmekisgoingtochooseareand .Inotherwords,thepairsofindicesthatErmek

planstochooseare , , , , ,and .

InthissettingAizhancansortthesequence intotheorder inthreerounds.Shecandosobychoosingtheindices , ,andthen .

ThefollowingtableshowshowErmekandAizhanmodifythesequence.

Page 13: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/3

Round Player Pairofswappedindices Sequencebeginning

ErmekAizhanErmekAizhanErmekAizhan

Round Player Pairofswappedindices Sequence

Example2

Supposethat:

Theinitialsequenceis .

Ermekiswillingtomake swaps.

ThepairsofindicesthatErmekplanstochooseare , , , ,and .

InthissettingAizhancansortthesequence inthreerounds,forexamplebychoosingthepairsofindices , ,andthen .ThefollowingtableshowshowErmekandAizhanmodifythesequence.

Round Player Pairofswappedindices Sequencebeginning

ErmekAizhanErmekAizhanErmekAizhan

TaskYouaregiventhesequence ,thenumber ,andthesequencesofindices and .Computeasequenceofswaps,whichAizhancanusetosortthesequence .Insubtasks and thesequenceofswapsyoufindhastobetheshortestpossible.

YouneedtoimplementthefunctionfindSwapPairs:findSwapPairs(N,S,M,X,Y,P,Q) —Thisfunctionwillbecalledbythegraderexactlyonce.

N:thelengthofthesequence .

S:anarrayofintegerscontainingtheinitialsequence .

Page 14: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

3/3

M:thenumberofswapsErmekplanstomake.

X,Y:arraysofintegersoflength .For ,inround Ermekplanstoswapnumbersatindices and .

P,Q:arraysofintegers.UsethesearraystoreportonepossiblesequenceofswapsAizhancanmaketosortthesequence .Denoteby thelengthofthesequenceofswapsthatyourprogramhasfound.Foreach between and inclusive,theindicesAizhanshouldchooseinround shouldbestoredinto and .YoumayassumethatthearraysPandQhavealreadybeenallocatedto elementseach.

Thisfunctionshouldreturnthevalueof (definedabove).

Subtasks

subtask points extraconstraintsonX,Y requirementonR1 8 forall2 12 forall3 16 forall4 18 none5 20 none minimumpossible6 26 none minimumpossible

Youmayassumethatthereexistsasolutionthatrequires orfewerrounds.

SamplegraderThesamplegraderreadstheinputfromthefilesorting.ininthefollowingformat:

line1:Nline2:S[0]…S[N-1]line3:Mlines4,…,M+3:X[i]Y[i]

Thesamplegraderprintsthefollowingoutput:

line1:thereturnvalue offindSwapPairsline2+ ,for :P[i]Q[i]

Page 15: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

1/3

InternationalOlympiadinInformatics201526thJuly-2ndAugust2015Almaty,KazakhstanDay2

townsLanguage:en-ISC

TownsThereare smalltownsinKazakhstan,numberedfrom through .Thereisalsoanunknownnumberoflargecities.ThesmalltownsandlargecitiesofKazakhstanarejointlycalledsettlements.

AllthesettlementsofKazakhstanareconnectedbyasinglenetworkofbidirectionalhighways.Eachhighwayconnectstwodistinctsettlements,andeachpairofsettlementsisdirectlyconnectedbyatmostonehighway.Foreachpairofsettlements and thereisauniquewayinwhichonecangofrom to usingthehighways,aslongasnohighwayisusedmorethanonce.

Itisknownthateachsmalltownisdirectlyconnectedtoasingleothersettlement,andeachlargecityisdirectlyconnectedtothreeormoresettlements.

Thefollowingfigureshowsanetworkof smalltownsand largecities.Smalltownsaredepictedascirclesandlabeledbyintegers,largecitiesaredepictedassquaresandlabeledbyletters.

Everyhighwayhasapositiveintegerlength.Thedistancebetweentwosettlementsistheminimumsumofthelengthsofthehighwaysoneneedstotravelinordertogetfromonesettlementtotheother.

Foreachlargecity wecanmeasurethedistance tothesmalltownthatisthefarthestawayfromthatcity.Alargecity isahubifthedistance isthesmallestamongalllargecities.Thedistancebetweenahubandasmalltownthatisfarthestawayfromthehubwillbedenotedby .Thus, isthesmallestofallvalues .

Intheaboveexamplethefarthestsmalltownfromcity istown ,andthedistancebetweenthemis.Forcity wealsohave .(Oneofthesmalltownsthatare

farthestawayfrom istown6.)Theonlyhubintheaboveexampleiscity ,with .Hence,intheaboveexample is .

Removingahubdividesthenetworkintomultipleconnectedpieces.Ahubisbalancedifeachof

Page 16: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

2/3

thosepiecescontainsatmost smalltowns.(Westressthatwedonotcountthelargecities.)Notethat denotesthelargestintegerwhichisnotgreaterthan .

Inourexample,city isahub.Ifweremovecity ,thenetworkwillbreakintofourconnectedpieces.Thesefourpiecesconsistofthefollowingsetsofsmalltowns:{ },{ },{ },and{ }.Noneofthesepieceshasmorethan smalltowns,hencecity isabalancedhub.

TaskInitially,theonlyinformationyouhaveaboutthenetworkofsettlementsandhighwaysisthenumberofsmalltowns.Youdonotknowthenumberoflargecities.Youalsodonotknowanythingabout

thelayoutofhighwaysinthecountry.Youcanonlyobtainnewinformationbyaskingqueriesaboutdistancesbetweenpairsofsmalltowns.

Yourtaskistodetermine:

Inallsubtasks:thedistance .

Insubtasks3to6:whetherthereisabalancedhubinthenetwork.

YouneedtoimplementthefunctionhubDistance.Thegraderwillevaluatemultipletestcasesinasinglerun.Thenumberoftestcasesperrunisatmost .ForeachtestcasethegraderwillcallyourfunctionhubDistanceexactlyonce.Makesurethatyourfunctioninitializesallnecessaryvariableseverytimeitiscalled.

hubDistance(N,sub)N:thenumberofsmalltowns.sub:thesubtasknumber(explainedintheSubtaskssection).Ifsubis1or2,thefunctioncanreturneither or

Ifsubisgreaterthan2,ifthereexistsabalancedhubthenthefunctionmustreturn ,otherwiseitmustreturn .

YourfunctionhubDistancecanobtaininformationaboutthenetworkofhighwaysbycallingthegraderfunctiongetDistance(i,j).Thisfunctionreturnsthedistancebetweenthesmalltownsand .Notethatif and areequal,thefunctionreturns .Italsoreturns whentheargumentsareinvalid.

SubtasksIneachtestcase:

isbetween and inclusive.

Thedistancebetweenanytwodistinctsmalltownsisbetween1and1,000,000inclusive.

Thenumberofqueriesyourprogrammaymakeislimited.Thelimitvariesbysubtask,asgiveninthetablebelow.Ifyourprogramtriestoexceedthelimitonthenumberofqueries,itwillbeterminatedanditwillbeassumedtohavegivenanincorrectanswer.

Page 17: Boxes with souvenirs - NTNUtoi.csie.ntnu.edu.tw/file/20160120090541.pdf · Boxes with souvenirs The last act of the IOI 2015 opening ceremony is in progress. During the opening ceremony,

3/3

subtask points numberofqueries

findbalancedhub additionalconstraints

1 13 NO none

2 12 NO none

3 13 YES none

4 10 YES eachlargecityisconnectedtoexactlythreesettlements

5 13 YES none6 39 YES none

Notethat denotesthesmallestintegerwhichisgreaterthanorequalto .

SamplegraderNotethatthesubtasknumberisapartoftheinput.Thesamplegraderchangesitsbehavioraccordingtothesubtasknumber.

Thesamplegraderreadstheinputfromfiletowns.ininthefollowingformat:line1:Subtasknumberandthenumberoftestcases.

line2: ,thenumberofsmalltownsinthefirsttestcase.

following lines:The -thnumber inthe -thoftheselines isthedistancebetweensmalltowns and .

Thenexttestcasesfollow.Theyaregiveninthesameformatasthefirsttestcase.

Foreachtestcase,thesamplegraderprintsthereturnvalueofhubDistanceandthenumberofcallsmadeonseparatelines.

Theinputfilecorrespondingtotheexampleaboveis:

11110171820171220162320111702325221725212825161823012211624202724172025120231826222926191722212309211726231612171618901612211811202524262116010292619162120221712100252215232827292621292502122202524262318262221019111617191611191522190

Thisformatisquitedifferentfromspecifyingthelistofhighways.Notethatyouareallowedtomodifysamplegraders,sothattheyuseadifferentinputformat.