question
stringlengths
58
4.29k
label
class label
3 classes
the Road Accident band plan unprecedented tour Treeland the RA fan look forward event make bet concert favorite group haveTreeland consist n city pair city connect bidirectional road overall country n1 road we know possible city the city number integer 1 n for city know value ri number people itWe know band travel path have concert city path the band path pass city twice time city have not previously visit thus musician travel path visit city twice necessarily city way concertsthe band plan gather big stadium concert hall tour time perform city population large population previously visit concert city in word sequence population city concert hold strictly increasingin recent interview leader road accident band promise fan band concert large possible number city thus band travel chain city Treeland concert city population number increase number concert large possiblethe fan Treeland frantically try figure concert group Treeland look like can not manage help real programmer help fan find seek number concert
1graph
Polycarpus like give present Paraskevi he buy chocolate bar shape segment rectangle the bar a1b1 segment large second a2b2 segment largePolycarpus want Paraskevi bar lunch break eat besides want polycarpuss mind Paraskevis beauty equally match bar number squaresTo bar number square Polycarpus eat little piece chocolate minute each minute follow break bar exactly half vertically horizontally eat exactly half bar chip exactly bar vertically horizontally eat exactly bar in case leave half bar second case leave third barBoth variant are not possible Polycarpus chip half for example bar 1623 Polycarpus chip half if bar 2018 Polycarpus chip half if bar 57 Polycarpus chip half thirdwhat minimum number minute Polycarpus need bar consist number square find require minimum number minute possible size bar process
1graph
you positive integer m nonnegative integer s your task find small large number length m sum digit s the require number nonnegative integer write decimal base lead zero
1graph
there old tradition keep 4 box candy house Cyberland the number candy special arithmetic mean median range equal by definition set x1x2x3x4 x1x2x3x4 arithmetic mean median range x4x1 the arithmetic mean median necessary integer it wellknown number box create debug field code field bugsFor example 1133 example 4 number meet condition mean median range equal 2Jeff 4 special box candy however bad happen some box lose n 0n4 box remain the ith remain box contain ai candiesNow Jeff want know possible way find number candy 4n miss box meeting condition mean median range equal
2string
there n city Cyberland number 1 n connect m bidirectional road the jth road connect city aj bjFor tourist souvenir sell city Cyberland in particular city sell price winow q query handle there type query C w the price city change w a b now tourist travel city b he choose route do not want visit city twice he buy souvenir city souvenir cheap possibly exactly city b you output minimum possible price buy souvenir travelmore formally define route follow a route sequence city x1x2xk k certain positive integer for 1ijkxixj for 1ik road connect xi xi1 the minimum price route minwx1wx2wxk the require answer minimum value minimum price valid route b
2string
as know undirecte connect graph n node n1 edge call tree you give integer d tree consist n node each node value ai associate itWe set S tree nod valid follow condition satisfy S nonempty S connect in word nod u v S node lie simple path u v present S your task count number valid set since result large print remainder modulo 1000000007 1097
1graph
you friend you want present positive integer you want present cnt1 number friend cnt2 number second friend moreover want present number distinct mean number present friendsIn addition friend like number divisible remainder prime number x the second like number divisible remainder prime number y of course you re go present friend number do not likeyour task find minimum number v form present number set 12v of course choose present number alla positive integer number great 1 call prime positive divisor 1
1graph
well array n nonnegative integer a1a2an interesting meet m constraint the ith m constraints consist integer li ri qi 1lirin meaning value equal qi your task find interesting array n element state array do not existexpression xy mean bitwise and number x y in programming language C Java Python operation represent Pascal
1graph
permutation p order set integer p1p2pn consist n distinct positive integer large n well denote n length permutation p1p2pnyour task find permutation p length n group number p1p2p2p3pn1pn exactly k distinct element
1graph
Dreamoon see large integer x write ground want print binary form Dreamoon accomplish turn x binary format now go print follow mannerHe integer n0 perform follow operation order unlimited time Print n binary form lead zero print append right previous print increase n 1 Lets define ideal sequence sequence operation successfully print binary representation x lead zero end print operation ie operation 1 Dreamoon wants know different ideal sequence length operation short ideal sequencethe answer large print modulo 1000000007 1097let define string representation ideal sequence string 1 2 ith character string match ith operation perform two ideal sequence call different string representation different
1graph
mole hungry he find ant colony consist n ant order row each ant 1 in strength siin order dinner interesting Mole organize version Hunger Games ant he choose number l r 1lrn pair ant indice l r inclusively fight when ant j fight ant get battle point si divide sj ant j get battle point sj divide si after fight finish Mole make rank an ant vi battle point obtain go free virl word take point fight participate after Mole eat rest ant note ant free nonein order choose good sequence Mole give t segment liri ask ant go eat ant fight
0array
there task follow structure give model operation use operation achive goal one way create new task use model operation change goallet try I create follow task topcoder SRM 557 div1hard give n integer x1x2xn you allow perform assignment want follow form xi xj original task j different task allow equal j the goal maximize sum xiNow change goal you give n integer y1y2yn you x1x2xn exactly equal y1y2yn in word number xi equal yi
2string
polar bear Menshykov Uslada zoo St Petersburg elephant Horace zoo Kiev decide paint as try create masterpiece draft piece paper the draft consist n segment each segment horizontal vertical Now friend want simplify draft delete segment part segment final masterpiece meet condition Horace want able paint picture stroke put brush paper take picture ready the brush paint place multiple time that s remain segment form single connected shape Menshykov want result shape simple he define simple shape shape do not contain cycle Initially segment draft integer startpoint endpoint coordinate Uslada do not like real coordinate want condition fulfil change as part draft beautiful friend decide delete part draft sum length remain segment large possible your task count maximum sum length remain extra segment remove
1graph
its time polar bear Menshykov Uslada zoo St Petersburg elephant Horace zoo Kiev get business in total n task day animal task for task evaluate difficulty also animal decide task order difficulty unfortunately task difficulty order perform task varymenshykov Uslada Horace ask deal nuisance come individual plan the plan sequence describe order animal n task besides want unique plan therefore plan form different sequence you find require plan deliver sad news state impossible come distinct plan give task
1graph
hamming distance string equal length number position correspond symbol different you give string calculate distance
2string
you give array n integer for element output sum previous element for element output sum element array
1graph
this unpronounceable word mean simply fear number 666 you give string digit check scary person suffer phobia ie contain number 666 substring
1graph
little x tree consist n node number 1 n each edge tree positive length Lets define distance node v u denote dvu sum length edge short path v u a permutation p sequence n distinct integer p1p2pn 1pin Little X wants find permutation p sum maximal possible if multiple optimal permutation want find lexicographically small help task
2string
little X n distinct integer p1p2pn he want divide set a b the follow condition satisfied if number x belong set a number ax belong set a if number x belong set b number bx belong set b help Little x divide number set determine impossible
1graph
the new ITone 6 release recently George get keen buy unfortunately do not money George go work programmer now face follow problem workgiven sequence n integer p1p2pn you choose k pair integer l1r1l2r2lkrk1l1r1l2r2lkrknrili1min way value sum maximal possible help George cope task
2string
George recently enter BSUCP Berland State University Cool Programmers George friend Alex enter university now move dormitory George Alex want live room the dormitory n room total at moment ith room pi people living room accommodate qi people total piqi your task count room free place George Alex
1graph
Peter sequence integer a1a2an Peter want number sequence equal h he perform operation add segment lr add element sequence indice l r inclusive at Peter choose element beginning segment twice Similarly Peter choose element end segment twice in word segment l1r1 l2r2 Peter add follow inequality hold l1l2 r1r2how distinct way number sequence equal h print number way modulo 10000000071097 two way consider distinct segment is not way
1graph
Roma find new character game World Darkraft 2 in game character fight monster find advanced stuff let fight strong monstersThe character equip k distinct type item power item depend level positive integer number Initially character 1level item k typesAfter victory monster character find exactly new randomly generate item the generation process look follow firstly type item define k type probability then level new item define Lets assume level player item choose type equal t moment level new item choose uniformly integer segment 1 t1from new item current player item type Roma choose well ie great level equip level Roma chose the remain item sell coin Roma sell item level x type x coinsHelp Roma determine expect number earn coin victory n monster
1graph
Paul hate palindrome he assume stre s tolerable character p letter English alphabet s do not contain palindrome contiguous substring length 2 morepaul find tolerable string s length n help find lexicographically tolerable string length state string exist
2string
Gargari get bored play bishop solve problem try math homework in math book find k permutation each consist number 12n order now find length long common subsequence permutation can help GargariYou read long common subsequence httpsenwikipediaorgwikilongest_common_subsequence_problem
2string
Appleman Toastman like game today play game string follow rule Firstly Toastman tell Appleman string s t consist letter a b c d then Appleman build string s quickly possible initially string second append end current string contiguous substre tNow Toastman Appleman begin play game Toastman tell string t Appleman have not come stre s toastman think choose string s consist n character of course wants find bad string Appleman string Appleman spend time possible game Tell Toastman time Appleman spend game Toastman find bad string you assume Appleman play optimally build string s minimal possible time
1graph
Parmida clever girl want participate Olympiads year of course want partner clever he s Parmida prepare follow test problem PashmakThere sequence consist n integer a1a2an let denote flrx number indice k lkr akx his task calculate number pair indicie ij 1ijn f1iaifjnajhelp Pashmak test
1graph
there computer network consist n node number 1 n there link network connect pair nod a pair nod multiple link node link itselfeach link support unlimited bandwidth direction link transmit single direction give time the cost send datum link proportional square bandwidth specifically link positive weight cost send datum link weight time square bandwidthThe network connect series link node node furthermore design remain connected event single node failureYou need send data node 1 node n bandwidth positive number k that wish assign bandwidth link bandwidth node minus bandwidth node k node 1 k node n 0 node the individual bandwidth need integerswishing minimize total cost draw diagram network give task intern solve the intern claim solved task write optimal bandwidth diagram spill coffee render unreadable include part original diagram value kFrom information available determine intern solution optimal that determine exist valid network total bandwidth optimal solution superset give information furthermore determine efficiency intern solution possible efficiency define total cost divide total bandwidth
1graph
the game bingo play 55 square grid fill distinct number 1 75 in problem consider generalized version play nn grid distinct number 1 m mn2 a player begin select randomly generate bingo grid generate uniformly available grid then k distinct number 1 m call random call uniformly available set k number for call number appear grid player mark cell the score end 2 raise power number completely mark row plus number completely mark columnsdetermine expect value score the expected score large if expect score large 1099 print 1099 instead example 1e99 quote
1graph
the Elements Harmony supernatural artifact represent subjective aspect harmony they arguably powerful force Equestria the inside Elements Harmony see complete graph n vertex label 0 n1 n power equal 2 m the energy Elements Harmony constant movement accord ancient book energy vertex u time eiu equal here b transformation coefficient array m1 integer fuv number one binary representation number uxorvGiven transformation coefficient energy distribution time 0 e0 help Twilight Sparkle predict energy distribution time t et the answer large output modulo p
1graph
there n game football tournament three team participate currently k game play you avid football fan recently miss k game fortunately remember guess friend k game your friend tell exact number win team instead think absolute difference number win second team d1 second team d2You do not want team win tournament team number win n game that s want know exist valid tournament satisfy friend guess team win tournamentnote outcome match draw win loss
0array
Jzzhu pick n apple big apple tree all apple number 1 n now wants sell apple store Jzzhu pack apple group sell each group contain apple great common divisor number apple group great 1 of course apple groupJzzhu wonder maximum possible number group can help
2string
Bizon Champion is not bison he favorite Bizons teamAt competition Bizons got follow problem you give distinct word string English letter s t you need transform word s word t the task look simple guy know suffix data structure Bizon Senior love suffix automaton by apply string remove string single character Bizon Middle know suffix array by apply string swap character string the guy know suffix tree help Bizon Champion wonder bizon solve problem perhaps solution require data structure find guy solve problem can solve use suffix automaton use suffix array need structure Note structure unlimited number time structure order
1graph
DZY hash table p bucket number 0 p1 he want insert n number order give hash table for ith number xi DZY bucket number hxi hx hash function in problem assume hxxmodp Operation amodb denote take remainder division bHowever bucket contain element if DZY want insert number bucket fill conflict happen suppose conflict happen right ith insertion output if conflict happen output 1
1graph
in mathematical term sequence Fn Fibonacci number define recurrence relation f11f21fnfn1fn2n2dzy love Fibonacci number today DZY give array consist n integer a1a2an moreover m query query type Format query 1 l r in reply query need add Fil1 element ai lir Format query 2 l r in reply query output value modulo 10000000091099 help DZY reply query
2string
as know DZY love play game one day DZY decided play nm matrix to precise decide modify matrix exactly k operationseach modification follow Pick row matrix decrease element row p this operation bring DZY value pleasure equal sum element row decrease Pick column matrix decrease element column p this operation bring DZY value pleasure equal sum element column decrease DZY wants know large total value pleasure perform exactly k modification please help calculate value
1graph
DZY love planting enjoy solve tree problemsdzy weight tree connect undirected graph cycle contain n node number 1 n he define function gxy 1xyn long edge short path node x y Specially gzz0 zFor integer sequence p1p2pn 1pin DZY define fp DZY want find sequence p fp maximum possible value but restriction element j appear p xj timesplease find maximum possible fp describe restriction
1graph
Kolya get stre s birthday string consist small english letter he immediately add k character right stringThen Borya came say new string contain tandem repeat length l substre how large l besee note definition tandem repeat
2string
Gena do not like geometry ask solve problem himA rectangle side parallel coordinate axis contain n dot Lets consider point plane Lets count distance point give n point let sort number nondecrease order well beauty point second element array if mimimum element array beaty equal minimumFind maximum beauty point inside give rectangle
1graph
have play Hanabi if you ve get try this problem deal simplify version gameoverall game 25 type card 5 distinct color 5 distinct value Borya hold n card the game somewhat complicated fact everybody see Boryas card Borya Borya know card know order lie Note Borya multiple identical card 25 type card know exactly card type hasthe aim player achieve state Borya know color number value card for player hint the hint type color hint value hint a color hint go like player name color point card color similarly go value hint a player name value point card contain valuedetermine minimum number hint player Borya certain card color value
2string
a permutation p length n sequence distinct integer p1p2pn 1pin a permutation identity permutation follow equation hold pii a swap ij operation swap element pi pj permutation Lets assume fp minimum number swap need permutation p identity permutation Valera wonder transform permutation p permutation q fqm minimum number swap help
1graph
Valera love garden n fruit tree growthis year enjoy great harvest on ith tree bi fruit grow ripen day number ai unfortunately fruit tree wither collect day ai day ai1 fruit collect day unfit eatvalera fast positive point Valera ready work day in day Valera collect v fruit the fruit tree different one what maximum fruit Valera collect time operate optimally
1graph
Devu brother love lot as super geek like play array they give array b father the array give Devu b brother as Devu naughty kid want minimum value array maximum value brother array b now help Devu achieve condition you perform multiple operation array in single operation allow decrease increase element array 1 note allow apply operation index array multiple timesyou need find minimum number operation require satisfy Devus condition brother play peacefully fight
1graph
Devu renowned classical singer he invite big functionsfestival recently invite all World Classical Singing Festival other Devu comedian Churu invitedDevu provide organizer list song require time singe he sing n song ith song ti minute exactly the Comedian Churu crack joke all joke 5 minute exactlyPeople mainly come listen Devu but know need rest 10 minute song on hand Churu active person do not need restyou organizer optimal sсhedule event for reason follow condition the duration event d minute Devu complete song with satisfy previous condition number joke crack Churu possible if possible find way conduct song Devu output 1 otherwise find maximum number joke Churu crack grand event
2string
at childrens day child come Pickss house mess house pick angry a lot important thing lose particular favorite sequence PicksFortunately Picks remember repair sequence initially create integer array a1a2an then perform sequence m operation an operation follow Print operation lr Picks write value Modulo operation lrx Picks perform assignment aiaimodx lir Set operation kx Picks set value ak x word perform assignment akx can help pick perform sequence operation
2string
all modern mobile application divide free pay even single application developer release version pay version ad free version ad suppose pay version app cost p p integer ruble free version application contain c ad banner each user describe integer ai number ruble user willing pay pay version application bi number banner willing tolerate free versionthe behavior member shall consider strictly deterministic user value bi c use free version value ai p buy pay version advertising user simply use application each user free version bring profit cw ruble each user pay version bring profit p rublesyour task help application developer select optimal parameter p c namely know characteristic user value c 0 maxbi1 need determine maximum profit application corresponding parameter p
1graph
one day Okazaki Tomoya buy tree Furukawa Nagisas birthday the tree strange node tree value the value ith node vi Now Furukawa Nagisa Okazaki Tomoya want play game treelet se path node s node e write sequence value nod path se denote sequence Sse we define value sequence GSse follow Suppose sequence z0z1zl1 l length sequence we define GSsez0k0z1k1zl1kl1 if path se satisfy path se belong Furukawa Nagisa belong Okazaki TomoyaCalculating path easy want play difficult Furukawa Nagisa think path p1p2 p2p3 belong path p1p3 belong also think path p1p2 p2p3 belong Okazaki Tomoya path p1p3 belong Okazaki Tomoya but fact conclusion is not right so Furukawa Nagisa want know triplet p1p2p3 correct conclusion task
1graph
Kuriyama Mirai kill monster get n stone she number stone 1 n the cost ith stone vi Kuriyama Mirai want know stone ask kind question she tell number l r1lrn tell let ui cost ith cheap stone cost ith place arrange stone cost nondecrease order this time tell number l r1lrn tell for question correct answer Kuriyama Mirai fuyukai desu unhappy
1graph
Kitahara Haruki buy n apple Touma Kazusa Ogiso Setsuna now want divide apple friendseach apple weight 100 gram 200 gram of course Kitahara Haruki do not want offend friend therefore total weight apple give Touma Kazusa equal total weight apple give Ogiso SetsunaBut unfortunately Kitahara Haruki do not knife right split apple part please tell possible divide apple fair way friend
1graph
Iahub Sorin good competitive programmer town however can not qualify important contest the selection help single problem Blatnatalag friend Iahub manage hold problem contest because want sure Iahub qualified tell Iahub follow taskyoure give 1based array n element Lets define function fij 1ijn ij2gij2 Function g calculate follow pseudocodeint gint int j int sum 0 int k mini j 1 k maxi j k k 1 sum sum ak return sumfind value minijfijprobably Iahub figure solution problem can
1graph
Sereja paint n distinct point plane the coordinate point integer now wonder square side parallel coordinate axis point paint vertex help calculate number
0array
the administration Tomsk Region firmly believe time megacity population million instead improve demographic situation decide achieve goal expand boundary cityThe city Tomsk represent point plane coordinate 0 0 the city surround n location ith coordinate xi yi population ki people you widen city boundary circle radius r in case location inside circle border include cityYour goal write program determine minimum radius r necessary expand boundary Tomsk megacity
2string
recently bug find FOS code the head F company wants find culprit punish for set organizational meeting issue who s bugged code each n coder meeting say I know sure x y itThe head company decide choose suspect invite office naturally consider coder opinion that s head want choice p n coder agree a coder agree choice suspect people name meeting choose suspect in way head F choose suspectsnote coder choose suspect agree head choice name choose coder meeting
1graph
in order ensure confidentiality access Russian Code Cup problem password protect problem development processTo select password jury generate special table contain n column infinite number row to construct table row fix obtain follow ruleIn row position p number equal number time ai1p occurs prefix ai11 pto ensure require level confidentiality jury able perform follow operation replace number a1p v rebuild table find number axy new password do step manually tedious jury ask help write program respond request jury
1graph
a boy name Gena want Russian Code Cup final tshirt but offer problem complex arrangement n friend solve problem himThe participant offer m problem contest for friend Gena know problem solve but genas friend will not agree help Gena ith friend ask Gena xi ruble help solve problem also friend agree write code Gena Genas computer connect ki monitor monitor cost b rublesGena careful money want spend little money possible solve problem help Gena tell spend small possible money initially there s monitor connect Genas computer
2string
one day Russian Code Cup event decide play football competition event all participant divide n team play match team play oncethe appoint Judge experience member Pavel but wise soon get bored game fall asleep Waking discover tournament team want know result matchesPavel do not want discover sleep keep eye result decide recover result game to ask team learn real winner friendship team beat team exactly k time help pavel come chronology tournir meet condition report table
1graph
Polycarpus develop interesting theory interrelation arithmetic progression world his current idea population capital Berland change time like arithmetic progression well like multiple arithmetic progressionspolycarpus belief write population capital consecutive year sequence a1a2an convenient consider array arithmetic progression write for example sequence 8642147102 consider sequence arithmetic progression 8642 14710 2 write anotherunfortunately Polycarpus datum n consecutive year census population do not occur year for reason value ai unknown such value represent number 1for give sequence aa1a2an consist positive integer value 1 find minimum number arithmetic progression Polycarpus need to progression need write Values 1 correspond arbitrary positive integer value ai0 equal correspond element seek consecutive record progressionsLet remind finite sequence c call arithmetic progression difference ci1ci consecutive element constant by definition sequence length 1 arithmetic progression
1graph
Mashmokh work factory at end day turn light the light factory index 1 n there n button Mashmokhs room index 1 n if Mashmokh push button index light index turn turn offmashmokh clever so instead push button push button randomly night he push m distinct button b1b2bm button push consecutively give order night now wants know light index button turn light please note index button bi actually bi iPlease help Mashmokh print index
2string
Mashmokh play new game in begin k liter water p coin additionally root tree undirecte connect acyclic graph consist m vertex each vertex tree contain water tank beginningthe game begin fact Mashmokh choose k tank root pour exactly 1 liter water then follow process perform water remained tank the process consist step at begin step Mashmokh open door tank then Mashmokh close door tank allow close door tank root duration Lets denote number liter tank close door w Mashmokh pay w coin closing tank Lets denote x1x2xm list vertex tree sort nondecrease depth the vertex list consider order firstly vertex x1 root empty then vertex xi i1 door close skip vertex water tank vertex xi tank father tank father close suppose l move tree Lets denote water inside tank root ith wi Mashmokh win maxw1w2wl dollar Mashmokh want know maximum dollar win playing game he ask find value
1graph
the product R2 company 2D games field new revolutionary algorithm search short path 2n mazeimagine maze look like 2n rectangle divide unit square each unit square cell obstacle in unit time person cell maze sideadjacent cell the short path problem formulate follow give free maze cell need determine minimum time require cell otherunfortunately develop algorithm work request find short path practice request occur you chief R2 programmer commission optimize algorithm find short path Write program effectively respond multiple request find short path 2n maze
2string
jeopardy intellectual game player answer question earn point Company Q conduct simplify Jeopardy tournament good it company by lucky coincidence old rival final company R1 company R2 the final n question m auction question nm regular question each question price the price ith question ai point during game player choose question at question auction player choose change price number current point strictly large price question the new price question original price great current number point player choose question the correct answer bring player point equal price question the wrong answer question reduce number player point value question pricethe game follow First R2 company select question question choose answer previous question correctly if answer question person choose choose againall R2 employee support team they want calculate maximum possible number point R2 team luck game correctly answer question perhaps go surprised problem entrust solve
1graph
not long ago company R2 buy company r1 consequently development field multicore processor now R2 laboratory testing R1 processorsthe testing go n step step processor get instruction temperature measure the head engineer R2 keep report record work processor write minimum maximum measure temperature notebook his assistant write temperature notebook unknown reason record mThe day engineer assistant file report m temperature however chief engineer doubt assistant write correctly naturally chief engineer do not doubt note so ask help give number n m min max list m temperature determine upgrade set m temperature set n temperature add nm temperature minimum temperature min maximum max
1graph
the research center Q develop new multicore processor the processor consist n core k cell cache memory consider work processorAt cycle core processor get instruction number memory cell core write information cell after receive command core execute immediately sometimes happen cycle multiple core try write information single cell unfortunately developer foresee possibility resolve conflict core case deadlock core correspond memory cell lock forever each lock core ignore command core future able record information lock cell if core tries write information lock cell immediately lockedThe development team want explore deadlock situation therefore need program simulate processor give set instruction core m cycle you re lucky interesting work entrust accord instruction m cycle define core number cycle lock it believe initially core memory cell lock
1graph
a B example easy problem possible contest platform however scientist observe problem easy accept want try
2string
InputThe input contain single integer 1a64outputoutput single integerExamplesInput2Output1Input4Output2Input27Output5Input42Output6
2string
once little Vasya read article magazine beautiful handmade garland color paper Vasya immediately go store buy n color sheet paper area sheet 1 square meterThe garland consist exactly m piece color paper arbitrary area piece certain color to garland Vasya arbitrarily cut exist colored sheet piece Vasya oblige use sheet garlandVasya want garland attractive possible wants maximize total area m piece paper garland Calculate maximum total area piece paper garland Vasya
1graph
little Chris huge fan linear algebra this time give homework unusual square square matrixthe dot product integer number vector x y size n sum product correspond component vector the unusual square nn square matrix a define sum n dot product the ith dot product ith row vector ith column vector matrix AFortunately Chris work GF2 this mean operation addition multiplication calculate modulo 2 in fact matrix a binary element a 0 1 for example consider follow matrix a the unusual square a equal 1110110111101101000110however homework Chris process q query query follow give row index flip value ith row a give column index flip value ith column a find unusual square a to flip bit value w mean change 1w ie 1 change 0 0 change 1given initial matrix a output answer query type can solve Chriss homework
1graph
Valera undirecte connected graph selfloop multiple edge consist n vertex the graph interesting property k edge adjacent vertex for convenience assume graph vertex index integer 1 nOne day Valera count short distance graph vertex one write array d thus element di array show short distance vertex Valera choose vertex number iThen irreparable terrible happen Valera lose initial graph however array d help restore lost graph
1graph
Valera take Berland Marathon the marathon race start stadium represent plane square low left corner locate point coordinate 00 length equal meter the side square parallel coordinate axesAs length marathon race long Valera need extra drink race the coach give Valera bottle drink d meter path we know Valera start point coordinate 00 run counterclockwise that Valera cover meter reach point coordinate a0 we know length marathon race equal nd05 meter help valeras coach determine locate help Valera specifically determine coordinate Valeras position cover d2dnd meter
1graph
Inna feed joke female logic so start binary logic insteadInna array n element a11a12a1n girl like train binary logic exercise consist n stage stage Inna write number array a1 ith i2 stage girl write element array ai consist ni1 integer kth integer array ai define follow aikai1kandai1k1 here and bitwise binary logical operationDima decide check innas skill he ask Inna change array perform exercise sum element write current exercisehelp Inna answer question
1graph
Alexey merry Berland entrant get sick gray reality zealously want university there lot university nowadays Alexey getting lose diversity decide profession want at school bad grade subject thank wealthy parent able obtain graduation certificatethe situation complicate fact high education institution determine voluntary donation pay new student admission ni berubley he pay ni difference pay ni regard bribeeach rector wear distinctive uniform university therefore uniform pocket contain coin denomination ri the rector carry coin denomination li pocket pay small coin gather lot weight pocket tear therefore donation pay coin denomination x berubley lixri Berland use coin positive integer denomination Alexey use coin different denomination use coin denomination number time when Alexey confront order puzzle turn university accept Alexey afraid go army long want green uniform dad say army bully beat son pay ensure boy safety so Alexey want know sure university enter quickly choose alma materthank parent Alexey limit money assume unlimited number coin typein word give t request contain number niliri for query need answer possible gather sum exactly ni berubley coin integer denomination li ri berubley you use coin different denomination coin denomination number time
0array
the Minister education come naturally want perform poorly honor guest however hour arrival turn class malfunction lightbulb reason do not energy the solution find quickly we ve get change location lightbulb get maximum energyEverybody know power lightbulb equal C constant value ri Euclidean distance bulb ith generator Consequently task minimize of course know position generatorsThe bulb ceiling class the ceiling class form strictly convex mgon class form right prism strictly convex mgon Help find optimum location bulb Assume generator plane class ceiling consider plane class ceiling cartesian coordinate system introduce
2string
Alice like word nineteen she string s want string contain word possible for reason rearrange letter stringfor example string xiineteenppnnnewtnee string xnineteenppnineteenw contain occurrence mark word more formally word nineteen occur string number time read start letter string of course should not skip lettershelp find maximum number nineteen string
1graph
everyone know Fibonacci sequence this sequence define recurrence relation F11F22FiFi1Fi2i2Well define new number sequence Aik formula AikFiiki1In problem task calculate follow sum A1kA2kAnk the answer large print modulo 1000000007 1097
1graph
this problem consist subproblem solve subproblem F1 receive 8 point solve subproblem F2 receive 15 point solve subproblem F3 receive 10 pointsManao develop model predict stock price company n day want design profitmaximize trading algorithm use prediction unfortunately Manaos trading account follow restriction it allow own zero share stock time it allow buy sell share stock day it allow maximum k buy order n day for purpose problem define trade act buy share stock day hold stock day ji point share sell to restate constraint Manao permit k nonoverlapping trade course nday trading period Manaos model prediction stock priceeven restriction limit profit Manao compare achievable unlimited number trade ability hold share time Manao potential lot money Manaos model perfectly predict daily price stock for example model Manao wait price low buy share hold price reach high value sell profit repeat process k time n day passednevertheless Manao satisfied have merely good trading algorithm want develop optimal strategy trading subject constraint help Manao achieve goal write program determine buy sell stock achieve great possible profit nday trading period subject constraint
2string
this problem consist subproblem solve subproblem F1 receive 8 point solve subproblem F2 receive 15 point solve subproblem F3 receive 10 pointsManao develop model predict stock price company n day want design profitmaximize trading algorithm use prediction unfortunately Manaos trading account follow restriction it allow own zero share stock time it allow buy sell share stock day it allow maximum k buy order n day for purpose problem define trade act buy share stock day hold stock day ji point share sell to restate constraint Manao permit k nonoverlapping trade course nday trading period Manaos model prediction stock priceeven restriction limit profit Manao compare achievable unlimited number trade ability hold share time Manao potential lot money Manaos model perfectly predict daily price stock for example model Manao wait price low buy share hold price reach high value sell profit repeat process k time n day passednevertheless Manao satisfied have merely good trading algorithm want develop optimal strategy trading subject constraint help Manao achieve goal write program determine buy sell stock achieve great possible profit nday trading period subject constraint
1graph
this problem consist subproblem solve subproblem d1 receive 3 point solve subproblem D2 receive 16 pointsManao chief architect involve plan new supercollider he identify plot land large possible supercollider build the supercollider building require fourway orthogonal collision particle travel speed consist accelerate chamber shape like plus sign ie each accelerate chamber length align Earths magnetic field parallel orthogonal minimize interferencethe accelerate chamber need lay long flat stretch land cost control Thus Manao commission topographical study identify possible maximal length tract land available building accelerate chamber parallel orthogonal Earths magnetic field to build large possible supercollider Manao identify large symmetric plus shape candidate tract that find tract land form axisaligne plus shape large distance center plus tip short arm plus Note collider need use entire length tract identify example note
1graph
you receive 5 point solve problemManao invent new operation string call fold each fold happen pair consecutive letter place second string run opposite direction align position fold use operation Manao convert string structure level fold operation perform See follow example claritywe denote position fold character for example word ABRACADABRA write ABRACADABRA indicate fold times leftmost pair b r letter second a D rightmost pair b r letter here example fold stringsABCDEFGHIJK ABCDEFGHIJK ABRACADABRA XXXXXXXXXXXXXX XXXXXX KJIHG KJIHGFEDCB AR X abcdef a DAB X acar xxxxx AB XOne example ABCDEFGHIJK KIJHGFEABCDManao notice fold string view pile letter for instance previous example pile read AHI BGJK CF DE Manao wonder high pile identical letter build fold operation give word note pile contain gap start level for example rightmost example pile consider valid gap start level
2string
Inna love sweet that s wants play Sweet Matrix game Dima Sereja but Sereja large person game prove small Sereja suggest play large Sweet Matrix gameThe large Sweet Matrix playing field nm matrix Lets number row matrix 1 n column 1 m Lets denote cell ith row jth column ij each cell matrix contain multiple candy initially cell the game go w move follow event occur Sereja choose integer x1y1x2y2v x1x2y1y2 add v candy matrix cell ij x1ix2y1jy2 Sereja choose integer x1y1x2y2 x1x2y1y2 then ask Dima calculate total number candy cell ij x1ix2y1jy2 ask Inna calculate total number candy cell matrix pq meet follow logical criterion px1 or px2 and qy1 or qy2 finally Sereja ask write difference number Dima calculate number Inna calculate D I unfortunately Serejas matrix huge that s Inna Dima are not cope calculate help
1graph
Inna love sleep need n alarm clock total wake Lets suppose innas room 100100 square low left corner point 00 upper right corner point 100100 then alarm clock point integer coordinate squarethe morning come all n alarm clock Innas room ring Inna want turn for Inna come amusing game First Inna choose type segment use game the segment vertical horizontal then Inna make multiple move in single Inna paint segment length plane choose type beginning game vertical horizontal alarm clock segment switch the game end alarm clock switch Inna sleepy want alarm clock soon possible help find minimum number move game need turn alarm clock
2string
Fox Ciel play game number Ciel n positive integer x1 x2 xn she follow operation time need select different index j xi xj hold apply assignment xi xi xj the goal sum number small possibleplease help Ciel find minimal sum
1graph
Fox Ciel study number theoryshe think nonempty set S contain nonnegative integer perfect equal b where operation xor mean exclusive operation httpenwikipediaorgwikiexclusive_orplease calculate number perfect set consist integer great k the answer large print modulo 1000000007 1097
1graph
George decide prepare Codesecrof round prepared m problem round Lets number problem integer 1 m George estimate ith problem complexity integer biTo round good need n problem besides need problem complexity exactly a1 complexity exactly a2 complexity exactly of course round problem complexitiesgeorge poor imagination its easy prepared problem simple come new prepare George magnificent simplify problem he simplify prepared problem complexity c positive integer complexity d cd change limit input dataHowever simple George understand simplifie problem run problem good round that s decide find minimum number problem need come addition m he s prepared order good round Note George come new problem complexity
1graph
string diversity number symbol occur stre diversity s denote ds for example daaa1 dabacaba3Given string s consist lowercase latin letter consider substring obviously substre diversity number 1 d Find statistic substring diversity k 1 d find substring s diversity exactly k
2string
in problem consider special type auction call secondprice auction as regular auction n bidder place bid price bidder ready pay the auction close bidder secretly inform organizer auction price willing pay after auction winner participant offer high price however pay price offer high price offer participant secondprice auctionWrite program read price offer bidder find winner price pay Consider offer price different
2string
Iahub want enhance multitaske ability in order want sort n array simultaneously array consist m integersiahub choose pair distinct index j 1ijmij then array value position j swap value position strictly great value position jIahub want find array pair distinct index choose order sort n array ascend descend order particular order give input the size array pair help Iahub find suitable array
1graph
Ksenia ordinary pan scale weight equal mass Ksenia weight scale weight untouched Ksenia wonder possible remain weight scale scale equilibrium the scale equilibrium total sum weight leave pan equal total sum weight right pan
1graph
sereja bracket sequence s1s2sn word stre s length n consist character Sereja need answer m query describe integer liri 1lirin the answer ith query length maximum correct bracket subsequence sequence slisli1sri help Sereja answer queriesyou find definition subsequence correct bracket sequence note
1graph
Sereja adore tree today come revolutionary new type binary root treeshis new tree consist n level vertex index integer number level number vertex current level the tree root level 1 index 11 here pseudo code tree constructionthe global data integer array cnt leave rightcnt1 1fill array leave right value 1forlevel 1 level n level level 1 cntlevel 1 0 forposition 1 position cntlevel position position 1 ifthe value position power 1 2 4 8 leftlevelposition cntlevel 1 1 rightlevelposition cntlevel 1 2 cntlevel 1 cntlevel 1 2 rightlevelposition cntlevel 1 1 cntlevel 1 cntlevel 1 1 after pseudo code run cell cntlevel contain number vertex level level cell leftlevelposition contain number vertex level level1 leave child vertex index levelposition contain 1 vertex do not leave child similarly cell rightlevelposition responsible right child you tree n4 look like notesSerja love thing complicate tree add set Alevelposition vertex then Sereja execute m operation each operation follow type the format operation 1 t l r x for vertex levelposition leveltlpositionr add value x set Alevelposition the format operation 2 t v for vertex levelposition leveltpositionv find union set vertex subtree vertex levelposition Print size union set help Sereja execute operation in problem set contain distinct value like stdset c
1graph
soon hold world large programming contest testing system m bug the contest organizer wellknown university choice attract university student fix bug the university n student able perform work the student realize hope organizer do not want work free ith student want ci pass subject regardless volume workbugs like student bug characterize complexity aj student level ability bi student fix bug j level ability complexity bug biaj day Otherwise bug fix student of course student work bug day all bug dependent correct order different student work simultaneouslyThe university want fix bug quickly possible give student total s pass Determine student use come schedule work say student fix bug
1graph
Inna love digit 9 that s ask Dima write small number consist nine but Dima misunderstood write large number consist digit 1 9inna want slightly alter number Dima write end number contain digit possible in Inna choose adjacent digits number sum equal 9 replace single digit 9for instance Inna alter number 14545181 like 14545181194518119451919919 also use method transform number 14545181 number 19991 Inna transform 149591 number 19919 19991 contain digit nineDima programmer wants find distinct number contain digit possible Inna write number help challenge task
0array
there nm rectangular grid cell grid contain single integer zero Lets cell ith row jth column ijlet define rectangle integer abcd 1acn1bdm rectangle denote set cell grid xyaxcbyd Lets define good rectangle rectangle include cell zerosYou answer follow q query calculate number good rectangle cell give rectangle
2string
this task exclusively concentrate array element equal 1 andor 2array kperiod length divisible k array b length k represent array b write exactly time consecutively in word array kperiodic period length kFor example array nperiodic n array length Array 212121 time 2periodic 6periodic array 121121121 time 3periodic 9periodicfor give array consist number find minimum number element change array kperiodic if array kperiodic require value equal 0
1graph
a Christmas party city S n child all child come mitten the mitten different color child leave right mitten color Lets color mitten number integer 1 m child number 1 n then ith child mitten color ciThe Party Santa Claus Father Frost russian granddaughter Snow Girl child dance richly decorate Christmas tree in fact bright diverse child want wear mitten distinct color the child decide swap mitten got leave right mitten end mitten distinct color all mitten size fit childrenThe child start exchange mitten haphazardly could not reach situation child pair mitten distinct color Vasily Petrov dad child note general case children idea turn impossible besides mathematician come scheme distribute mitten number child distinctcolore mitten maximum you task repeat discovery Note leave right mitten different child end leave right mitten
1graph
Valera love segment he recently come interesting problemThe Ox axis coordinate n segment ith segment start position li end position ri mark liri your task process m query consist number cnti set cnti coordinate point locate Ox axis the answer query number segment contain point query Segment lr contain point q lqrValera find solution problem difficult so ask help help Valera
2string
one fine morning n fool line row after number number 1 n inclusive each fool get unique number the fool decide change number end funevery fool exactly k bullet pistol in addition fool number probability pi percent kill fool shoot atthe fool decide round fun each round fun look like currently live fool shoot live fool small number fool stupid shoot all shot round perfome time simultaneously if exactly live fool shootlet define situation set number live fool time we situation possible integer number j 0jk nonzero probability j round fun situation occurValera know number p1p2pn k Help Valera determine number distinct possible situation
1graph
sereja array consist n integer a1 a2 the boy sit decide study array Sereja take piece paper write m integer l1l2lm 1lin for number li wants know distinct number stay position li li1 n formally want find number distinct number aliali1ansereja write necessary array element array large boy press time Help find answer describe question li
1graph
Sereja sequence b number p Sequence consist n integer a1a2an similarly sequence b consist m integer b1b2bm as usual Sereja study sequence today want find number position q qm1pnq1 sequence b obtain sequence aqaqpaq2paqm1p rearrange elementssereja need rush gym ask find describe position q
2string
Dima love Inna he decide write song Dima magic guitar n string m fret Dima make guitar produce sound like play note need hold string fret pull string when Dima pull ith string hold jth fret guitar produce note let denote aij we know Dimas guitar produce k distinct note it possible note produce multiple way in word possible aijapq ijpqDima write song sequence s note in order play song need consecutively produce note song guitar you produce note available way Dima understand way play song want play song look complicated possible try act like CobeinWell represent way play song sequence pair xiyi 1is xith string yith fret produce ith note song the complexity move pair x1y1 x2y2 equal the complexity way play song maximum complexity move adjacent pairshelp Dima determine maximum complexity way play song the guy get to look cool
1graph
nothing change round Dima Inna love want they ve deal Seryozha need deal dorm guardsthere guardpost Dimas dorm each post contain guard Russia usually elderly woman you bribe guard chocolate bar box juice for guard know minimum price chocolate bar accept gift minimum price box juice accept gift if chocolate bar guard cost minimum chocolate bar price guard box juice guard cost minimum box juice price guard guard do not accept giftIn order pass guardpost need bribe guardsthe shop unlimited juice chocolate price start 1 Dima wants choose guardpost buy gift guard guardpost spend exactly n ruble ithelp choose post safely sneak Inna impossible Mind Inna sorry hear
2string