boxes with souvenirs - ntnutoi.csie.ntnu.edu.tw/file/20160120090541.pdf · boxes with souvenirs the...
TRANSCRIPT
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.
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
3/3
6 30subtask points
SamplegraderThesamplegraderreadstheinputinthefollowingformat:
line1:NKLline2:positions[0]…positions[N-1]
Thesamplegraderprintsthereturnvalueofdelivery.
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
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
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.
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.
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.
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.
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 .
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.
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.
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 .
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]
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
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.
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.