question
stringlengths
58
4.29k
label
class label
3 classes
in computer network Berland State University n router number 1 n some pair router connect patch cord information transmit patch cord direction the network arrange way communication router directly router possible there cycle network path pair router patch cordsunfortunately exact topology network lose administrator in order restore follow auxiliary information collectedFor patch cord p directly connect router list router locate patch cord p relatively known in word router path router go p know So router ki list ki number patch cord connect iFor example let network consist router connect chain 123 then router 1 single patch cord connect router single list contain router 2 3 router 2 patch cord connect second router list list contain router 1 router 3 router 3 single patch cord connect router single list contain router 1 2 your task help administrator restore network topology e identify pair router directly connect patch cord
2string
soon year student initiate student University Berland the organizer initiation come program holiday in opinion good firstyear student present small souvenir when voice idea firstyear student find follow pair new student know new student agree souvenir familiar new student want present souvenir the organizer write pair firstyear friend familiar want determine new student souvenir in opinion pair familiar student exactly student present souvenir studentFirst year student decide unluckiest present great number souvenir the organizer return promise unluckiest unlucky minimum possible degree course present great number souvenir compare student number small possibleorganizer busy ask determine pair firstyear friend present souvenir
1graph
polycarp plan conduct load test new project Fakebook he agree friend certain point time send request Fakebook the load testing n minute ith minute friend send ai requestspolycarp plan test Fakebook special kind load in case information Fakebook get mass medium Polycarp hope monotone increase load follow monotone decrease interest service Polycarp want test form loadyour task determine request Polycarp add moment load server strictly increase moment strictly decrease both increase decrease e absent the decrease immediately follow increase in particular load equal neigboure value unacceptablefor example load describe array 1 2 8 4 3 1 3 5 10 load satisfie Polycarp case increase immediately follow decrease if load describe array 1 2 2 1 2 1 2 10 10 load satisfy polycarphelp Polycarp minimum number additional request result load satisfie Polycarp he number additional request minute 1 n
1graph
doubly link list fundamental datum structure a doubly link list sequence element contain information previous element list in problem list linear structure Ie element exactly previous element element exactly element the list close cyclein problem give n memory cell form doubly link list each cell contain information element list memory cell number 1 nFor cell give value li cell contain previous element element cell ri cell contain element element cell if cell contain information element previous element li0 Similarly cell contain information element element ri0 three list show picture for example picture value l r follow l14 r17 l25 r20 l30 r30 l46 r41 l50 r52 l60 r64 l71 r70your task unite give list single list join order in particular input datum contain single list need perform action Print result list form value li riAny action join beginning list end perform
1graph
recently Luba buy monitor Monitor rectangular matrix size nm but start notice pixel cease work properly Luba think monitor broken moment contain square kk consist entirely break pixel she know q pixel break know moment stop work help Luba determine monitor break tell broken q pixel stop work
2string
polycarp take math he give n task consist k subtask number 1 k it take tj minute solve jth subtask task thus time require solve subtask depend index task Polycarp solve subtask orderBy solve subtask arbitrary problem earn point thus number point task equal number solve subtask Moreover Polycarp completely solve task solve k subtask recieve extra point thus total number point recieve complete solution task k1Polycarp M minute time what maximum number point earn
2string
polycarp great fan televisionHe write tv program interest today his list contain n show ith start moment li end moment ripolycarp own tv he watch different show simultaneously tv watch give moment single tv if end moment start can not watch single tvpolycarp want check n show Are tv
1graph
today lesson Vitya learn interesting function mex mex sequence number minimum nonnegative number present sequence element for example mex43301152 mex1230Vitya quickly understand task teacher sameyou give array consist n nonnegative integer m query each query characterize number x consist follow consecutive step perform bitwise addition operation modulo 2 xor array element number x find mex result array note query array change
1graph
one day Kefa find n baloon for convenience denote color ith baloon si lowercase letter latin alphabet also Kefa k friend Friend upset if baloon color Kefa want baloon friend help Kefa find baloon frien upset print yes no Note Kefas friend upset do not baloon
1graph
Lech get tree consist n vertex root vertex number 1 at vertex write integer ai he answer q query form u v Answer query maximal value vertice path u v include u v distiv number edge path v also guarantee vertex u ancestor vertex v Lehas taste singular believe vertex ancestor itselfhelp leha outthe expression mean bitwise exclusive or number x yNote vertex u ancestor vertex v vertex u lie path root vertex v
1graph
you give direct weighted graph n node 2n2 edge the node label 1 n edge label 1 2n2 the graph edge split part the n1 edge form root span tree node 1 root all edge point away root the n1 edge node node 1 2 in you give q query there type query 1 w Change weight ith edge w 2 u v Print length short path node u v give query print short path length
1graph
the cartesian coordinate system set sky there n star ith coordinate xi yi maximum brightness c equal star initial brightness si 0sicover time star twinkle at moment 0 ith star brightness si let moment t star brightness x then moment t1 star brightness x1 x1c 0 otherwiseYou want look sky q time in ith time look moment ti rectangle side parallel coordinate axis low left corner coordinate x1i y1i upper right x2i y2i for view want know total brightness star lie view rectangleA star lie rectangle lie border lie strictly inside
0array
recently wild Krakozyabra appear Jelly Castle it truth say eager dinnerits favorite meal natural number typically serve honey sauce precise zero correspond decimal representation as digit Krakozyabra dislikes cause indigestion so necessary precaution Krakozyabra prefer sort digits number nondescending order proceed feast then lead zero result number eat remain discard inedible tailfor example Krakozyabra number 57040 dinner inedible tail number 457slastyona fond idea Krakozyabra live castle Hovewer natural hospitality prevent leave guest food Slastyona range natural number L R go feed guest help determine distinct inedible tail going discard Krakozyabra end dinner
2string
its hard time today Petya need score 100 point informatic exam the task easy Petya think lack time finish ask help onethere glob pattern statement string consist lowercase english letter character it know character occur patternalso n query string give require determine pattern match noteverything easy Petya discover special pattern character differ usual meaningA pattern match stre possible replace character good lowercase english letter character include stre bad lowercase english letter result string give stringThe good letter give Petya all bad
1graph
there popular keyboard layout Berland differ letter position all key in Berland use alphabet 26 letter coincide English alphabetyou give string consist 26 distinct letter key second layout order you give text consist small capital english letter digit it know type layout writer intend type second layout print text key press second layoutsince key letter layout capitalization letter remain character
1graph
it know passage Singer house complex intertwine Lets define Singer khouse graph build follow process complete binary tree height k add edge vertex successor present Singer 4house Count number nonempty path Singer khouse pass vertex twice two path distinct set order visit vertex different since answer large output modulo 1097
2string
Vladimir want modernize partition office to office comfortable decide remove partition plant bamboos row he think nice n bamboo row ith left ai meter high Vladimir plant n bamboo row height 0 meter right grow 1 meter day in order partition nice Vladimir cut bamboo height great height bamboo bamboo stop growingVladimir want check bamboos d day ie d day plant 2d day cut bamboo reach require height Vladimir want total length bamboo part cut great k meterswhat maximum value d choose achieve want cut k meter bamboo
1graph
in small restaurant table person b table person it know n group people come today consist people if group consist person seat vacant oneseater table if seat vacant twoseater table if seated twoseater table occupy single person if restaurant deny service groupIf group consist people seat vacant twoseater table if restaurant deny service groupyou give chronological order group come you determine total number people restaurant deny service
1graph
Arkady need help this time decide build highspeed internet exchange point it consist n node connect minimum possible number wire network wire directly connect node exactly k node exitnode mean connect exactly node network node connect node order increase system stabilityArkady want system fast possible wants minimize maximum distance exitnode the distance node number wire package need nodesHelp Arkady find way build network distance distant exitnode small possible
2string
you give tree consist n vertex number 1 n initially vertex white you process q query different type 1 x change color vertex x black it guarantee query type 2 x vertex x find minimum index y vertex index y belong simple path x black vertex simple path visit vertex for query type 2 print answer itNote query give modified way
1graph
make solve problem decoforce lot different online judge each problem denote difficulty positive integer number difficulty measure judge problem difficulty d decoforce hard problem difficulty d judge Makes choose n problem solve Decoforces difficulty a1a2an he solve problem arbitrary order though solve problem difficulty ai solved problem difficulty matter online judge itBefore start choose list problem make solve problem maximum difficulty kWith give condition easy make can not solve choose problem matter order choose so want solve problem judge finish solve problem list for positive integer y exist problem difficulty y judge DecoforcesMakes solve problem judge time is not necessary problem choose list right anothermake do not free time ask calculate minimum number problem solve judge order solve choose problem decoforce
2string
Polycarp invent new binary protocol datum transmission he encode positive integer decimal number binary string follow algorithm each digit represent number 1 character equal value digit 0 zero one Digits write order correspond number separate single 0 character Though Polycarp learn encode number idea decode Help calculate decode number
1graph
the semester end you know end semester holiday begin on holiday Noora decide return Vičkopolis as modest souvenir Leha bring sausage length m Pavlopolis everyone know sausage represent string lowercase English letter length equal length sausageLeha pleased gift immediately eat sausage but realize tactless act sausage souvenir so hacker immediately go butcher shop unfortunately sausage length n shop however Leha upset buy sausage after come home decide cut purchase sausage piece number piece start 1 leave right then want select piece glue obtain sausage equal sausage Noora give but hacker glue piece number leave piece number right piece besides know glue x piece Noora notice falsify souvenir sausage upset of course Leha do not want upset girl the hacker ask find able cut sausage buy glue piece Noora do not notice anythingformally give string s t the length string s n length string t m it require select pairwise nonintersecte substring s concatenation order substring appear s equal string t Denote fst minimal number substring choose concatenation equal string t if impossible choose substring fst Leha want know true fstx
1graph
Okabe Super Hacker Daru stack remove box there n box number 1 n Initially box stackOkabe control freak give Daru 2n command n add box stack n remove box stack throw trash Okabe want Daru throw away box order 1 n of course mean impossible Daru perform Okabes remove command require box stackthat Daru decide wait Okabe look away reorder box stack way want he point time Okabes command can not add remove box itTell Daru minimum number time need reorder box successfully complete Okabes command it guarantee box add require remove
1graph
on quiet day sudden Mister B decide draw angle field Aliens visit field leave different geometric figure one figure regular convex ngon regular convex polygon n sidesthat Mister B decide use polygon now Mister B find distinct vertex v1 v2 v3 angle v2 vertex angle v1 v3 lie side close possible in word value minimum possibleif optimal solution Mister B satisfy
2string
in order fly Moon Mister B need solve follow problemthere complete indirecte graph n vertex you need cover simple cycle length 3 4 edge exactly 2 cycleswe sure Mister B solve problem soon fly Moon will
2string
Ivan develop computer game now try create level game but firstly level need draw graph represent structure levelIvan decide exactly ni vertex graph represent level edge bidirectional when construct graph Ivan interested special edge call bridge an edge vertex u v call bridge edge belong path u v vertex belong different connect component delete edge for level Ivan want construct graph half edge bridge he want maximize number edge construct graphSo task Ivan give give q number n1n2nq tell maximum number edge graph ni vertex half edge bridge note graph contain multiple edge selfloop
1graph
Captain Bill Hummingbird crew recieve interesting challenge offer some stranger give map potion teleportation say potion help reach treasure bottle potion value x y write these value define move perform potion Map show position Captain Bill Hummingbird x1y1 position treasure x2y2you task tell Captain Bill Hummingbird accept challenge decline if possible Captain reach treasure potion output yes no quotesthe potion infinite time
1graph
on way home Karen decide stop supermarket buy grocery she need buy lot good student budget limit in fact spend b dollarsThe supermarket sell n good the ith good buy ci dollar of course good buy oncelately supermarket try increase business Karen loyal customer give n coupon if Karen purchase ith good use ith coupon decrease price di of course coupon buying correspond goodthere constraint coupon for i2 order use ith coupon Karen use xith coupon mean coupon satisfy requirement couponKaren want know follow what maximum number good buy exceed budget b
1graph
Karen arrive school math test today the test basic addition subtraction unfortunately teacher busy write task Codeforces round time actual test so question test worth pointsThere n integer write row Karen alternately add subtract pair adjacent integer write sum difference row she repeat process value row integer remain the operation additionnote end previous row add integer start row subtract vice versaThe teacher simply look integer correct Karen get perfect score get zero testKaren study test scare mistake cause final answer wrong if process follow number expect write rowsince number large output nonnegative remainder divide 1097
1graph
sagheer work kindergarten there n child m different toy these child use welldefine protocol play toy each child lovely set toy love play he request toy distinct moment time a child start play grant toy lovely set if child start play soon later give toy no child keep toy forever child request toy distinct moment time no child request toy time if child grant toy give finish play lovely set if child grant toy wait grant toy he can not request toy wait if child wait toy child request toy firstChildren do not like play that s share toy when child request toy grant toy child depend toy free if toy free Sagheer child Otherwise child wait can not request toychildren smart detect wait forever toy want in case start cry in word cry set set child child wait toy keep child setnow reach scenario child request lovely set child x request lovely set some child play waiting toy child cry finish play if child x currently wait toy make request get toy otherwise make request right away when child x request child start cryingYou give scenario q independent query each query form x y mean request child x toy y your task help sagheer find size maximal crying set child x make request
1graph
Leha Noora decide trip Baltic States as know previous problem Leha lost car parking restaurant unfortunately request watchman do not help hacker find car friend decide hitchhikingin total intend visit n town however turn sight ith town open visitor day li riwhat Leha propose choose town day visit town ie integer xi interval liri after Noora chose subsequence town id1id2idk friend go visit strictly increase ie idiidi1 integer 1 k1 date friend visit strictly increase ie xidixidi1 true integer 1 k1Please help Leha Noora choose xi town subsequence town id1id2idk friend visit maximal number townsyou assume Leha Noora start trip day
0array
Vasya array consist positive integer number Vasya want divide array nonempty consecutive part prefix suffix sum element equal sum element second it possible Vasya element divide array Vasya erase element insert arbitrary positionInserting element position erase consider movingCan Vasya divide array choose right element new position
2string
in begin new year Keivan decide reverse he do not like palindrome change Naviek NavickHe selfish give n want obtain string n character b c palindrome length 3 appear string substre for example string abc abca suit string aba do not he want number letter c stre little possible
1graph
Seyyed MoJaK friend Sajjad Sajjad like permutation Seyyed want change permutation way Sajjad will not like Seyyed think swap yield probability make MoJaK perform swap pair position ij ij exactly MoJaK do not like upset SajjadGiven permutation determine possible swap pair position permutation stay if possible find
1graph
we string letter b we want perform operation on step choose substrings ab string replace string bba if ab substre job Print minimum number step perform job modulo 1097The string ab appear substre letter b right letter string
2string
a year ago Sajjad leave school register security reason now wish find Amir schoolmate good friendsThere n school numerate 1 n one travel pair need buy ticket the ticker school j cost multiple time help Sajjad find minimum cost need pay ticket visit school he start finish school
1graph
the main city magazine offer reader opportunity publish ad the format ad like thisThere spaceseparate nonempty word lowercase uppercase Latin lettersThere hyphen character word position set word wrapping point Word include hyphen it guarantee adjacent space adjacent hyphen no hyphen adjacent space there space hyphen word word when word wrap word hyphen hyphen stay current line word line you line break word case space stay current line check note well understandingthe ad occupy k lines minimal width the width ad maximal length string letter space hyphen count ityou write program find minimal width ad
1graph
the marmot need prepare k problem HC2 n day each problem prepare printedthe preparation problem day day cost ai CHF print problem day day cost bi CHF of course problem print prepared day finewhat minimum cost preparation printing
2string
Heidi terrified estimate find unrealistic friend collaborate drive debt she expect actually person pick random friend send Heidi this randomness assumption imply visit friend arbitrary number time Moreover person friend common Heidi ie person leaf tree person send Heidi Heidis travel end pointHeidi find unrealistic assumption travel day therefore assume time travel route friend need buy new ticket she want know expect spend tripsfor worth Heidi know Jenny friend
1graph
thank help Heidi confident fool she decide post fake news HC2 Facebook page however want able communicate HC2 committee post fake secret phrase hide post subsequence to method foolproof want phrase appear n time post she ask design post string s hide phrase p p appear s subsequence exactly n time
2string
your task exact easy version but time marmot subtract village population p random number respond Heidis requestalso village single inhabitant meaning can help Heidi find village follow Poisson uniform distribution
1graph
Heidi statistician core like study evolution marmot population V 1v100 village so come spring Heidi see snowdrop sprout meadow barn impatiently don snowshoes set Alps welcome friend marmot new season thrill adventuresarriving village Heidi ask marmot come number inhabitant village this year marmot decide play April Fools joke Heidi instead consistently provide exact number inhabitant p 10p1000 village respond random nonnegative integer k draw type probability distribution Poisson davril distribution probability get answer k k0123 Uniform distribution probability get answer k k0122P Heidi collect exactly 250 answer village every village follow Poisson uniform distribution Heidi tell marmot apart query marmot time time marmot answer new number draw village distributionCan help Heidi find village follow Poisson uniform distribution
1graph
Butler Ostin want Arkady row odd number fountain beautiful row number fountain notThe butler want Arkady n garden each garden row m cell ith garden fountain cell li ri inclusive fountain garden the issue garden contain number fountain wrong ArkadyOstin wants choose integers ab gardens start cell end cell b of course segment suit Ostin garden zero odd number fountain segment also necessary garden fountain segment bHelp Ostin find total length segment ie sum value ba1 suitable pair ab
1graph
Arkady play Gardenscapes lot Arkady want build new fountain there n available fountain fountain beauty cost know There type money game coin diamond fountain cost coin diamond no money change type allowedhelp Arkady find fountain maximum total beauty buy time
2string
in game Playrix take t minute oven bake k carrot cake cake ready moment t minute start bake Arkady need n cake complete task currently do not however infinitely ingredient oven moreover Arkady build similar oven process fast d minute build oven while new oven build old bake cake new oven build oven bake simultaneously Arkady can not build ovendetermine reasonable build second oven ie decrease minimum time need n cake if time need second oven oven unreasonable
2string
one day Masha come home notice n mouse corridor flat of course shout loudly scared mouse start run hole corridorthe corridor represete numeric axis n mouse m hole ith mouse coordinate xi jth hole coordinate pj jth hole room cj mouse cj mouse enter holewhat minimum sum distance mouse hide hole if ith mouse go hole j distance xipjprint minimum sum distance
1graph
Zane wizard love fall love girl remain unknown the girl live house m village there n house village line straight line leave right house 1 house 2 house n the village wellstructure house house i1 1 in exactly 10 meter away in village house occupy indeed unoccupied house purchasedYou give n integer a1a2an denote availability price house if house occupy buy ai equal 0 Otherwise house buy ai represent money require buy dollarsas Zane k dollar spare challenge choose house purchase live near possible crush Help Zane determine minimum distance crushs house house afford help succeed love
1graph
Oleg client Igor analyst good friend however argue little thing recently start new company have trouble find companyto settle problem they ve decide play game the company consist n letter Oleg Igor set n letter contain multiple copy letter set different Initially company denote n question mark Oleg Igor take turn play game Oleg move in turn player choose letter c set replace question mark c then copy letter c remove set the game end question mark replace letterFor example suppose Oleg set letter ioi Igor set letter imo one possible game follow Initially company Oleg replace second question mark the company the set letter Oleg ioigor replace question mark o the company io the set letter Igor imFinally Oleg replace question mark o the company oio the set letter Oleg iin end company oioOleg want company lexicographically small possible Igor want company lexicographically large possible what company Oleg Igor play optimallya string ss1s2sm call lexicographically small string tt1t2tm st siti small index siti sjtj ji
1graph
igor analyst adopt n little bunny as know bunny love carrot Thus Igor buy carrot share bunny Igor want treat bunny equally want cut carrot n piece equal area Formally carrot view isoscele triangle base length equal 1 height equal h Igor want n1 cut parallel base cut carrot n piece he want sure n piece area can help Igor determine cut carrot piece equal area Illustration example
1graph
there n city situate main road Berland Cities represent coordinate integer number a1a2an all coordinate pairwise distinctIt possible city bus but bus road old Minister Transport decide build new bus route the Minister do not want spend large amount money wants choose city way distance minimal possible the distance city equal absolute value difference coordinatesIt possible multiple pair city minimal possible distance Minister want know quantity pair your task write program calculate minimal possible distance pair city quantity pair distance
1graph
Rick love Unity but Mr Meeseeks love Unity Rick Mr Meeseeks love rival Unity love rap decide compete rap game battle order choose good Rick nerd instead he s go to verse run original algorithm lyric Rap God song his algorithm little bit complicated he s tree n vertex number 1 n there s lowercase english letter write edge he denote strab string write character edge short path b string length equal distance b note strab reverse strba straa in order good verse need answer query he s computer scientist able answer query ask help each query characterize vertex x y xy Answer query number vertex like z zxzy strxy lexicographically large strxzstre xx1x2xx lexicographically large string yy1y2yy xy x1y1x2y2xyyy exist number r rxry x1y1x2y2xryr xr1yr1 character compare like ascii code alphabetic orderHelp Rick girl gender Unity
0array
Anton like play chess also like program no wonder decide attend chess class program classesAnton n variant attend chess class ith variant give period time l1ir1i also m variant attend programming class ith variant give period time l2ir2iAnton need choose exactly n possible period time attend chess class exactly m possible period time attend programming class he want rest class possible pair period wants choose distance period maximalthe distance period l1r1 l2r2 minimal possible distance point period point second period minimal possible ij l1ir1 l2jr2 in particular period intersect distance 0anton wants know time rest class good case help Anton find number
2string
do you expect ME to find this outwhat base ANDXOR LANGUAGE include stringdont BYTE of MORE than you can chewyou can only distort the LARGEST of MATHEMATICS SO FARSAYING abracadabra without a MAGIC and WONT do you any GOODTHE last STACK ruptures all DIE OH the EMBARRASSMENTI have no ARRAY and I must screamelement may not BE store in WEST HYPERSPACE
1graph
a new bus route open city the route close polygon line place segment parallel axis m bus operate route all bus loop route direction equal constant velocity stop time negligible problembuse start movement vertex route equal interval suppose t total time single bus travel loop route then bus 1 start move time 0 bus 2 start time tm bus 3 start time 2Tm finally bus m start move time m1tm thus interval pair consecutive bus include interval bus equalbuse communicate wireless transmitter equal power if transmitter power d bus distance d communicatethe bus equip distribute system schedule track for bus stick schedule system synchronize necessary datum bus time time at moment synchronization bus 1 communicates bus 2 bus 2 bus 3 bus m communicates bus 1As research employee task find small value d possible find time moment perform synchronization bus start move
1graph
the evil Bumbershoot corporation produce clone gruesome experiment vast underground lab on occasion corp cloned boy Andryusha smart comrade immediately Andryusha understand fishy go he rally fellow clone feud evil corp set find exit lab the corp reduce destroy lab complexthe lab picture connect graph n vertex m edge k clone Andryusha start look exit vertex each clone traverse edge second any number clone allow vertex simultaneously each clone allow stop look time moment look start vertex the exit locate vertex lab vertex visit cloneeach clone visit vertex lab explodesyour task choose start vertex search route clone each route vertice
2string
innokenty president new football league Byteland the task assign short name club show tv score of course short name distinct Innokenty want short name consist lettersEach club consist word team hometowns example DINAMO BYTECITY Innokenty do not want assign strange short name wants choose short name club short letter team example mention club DIN letter short letter team letter letter hometown for mention club dib Apart rule club x second option short choose club option choose option club x for example mention club short dib club option choose short equal DIN however possible club short DIN DI letter team n letter hometown of course team short nameHelp innokenty choose short team if impossible report if multiple answer suit Innokenty if team option short equal Innokenty formally think option choose
1graph
Igor find discount shop decide buy n item discount store week Igor know item price ai week discount price biNot seller honest product expensive week discountsIgor decide buy k item wait rest week order save money possible your task determine minimum money Igor spend buy n item
1graph
Peterson love learn new language favorite hobby make new one Language set word word sequence lowercase Latin lettersPeterson make new language morning it difficult task store language Peterson invent new data structure store language call broom Broom root tree edge mark letter Initially broom represent vertex root broom when Peterson wants add new word language stand root process letter new word Consider Peterson stand vertex u if edge u mark current letter Peterson go edge Otherwise Peterson add new edge u new vertex v mark current letter go new edge Size broom number vertex itin evening work day Peterson can not understand language morning it difficult bored Peterson try simple Simplification language process erase letter word language Formally Peterson take positive integer p erase pth letter word language have length p Letters word index start 1 Peterson consider simplification change word ie word length p Peterson try language simple possible wants choose p size broom simplify language small possiblepeterson pretty annoyed task ask help write program find small possible size broom integer p
2string
little Nastya hobby like remove letter word obtain word but turn pretty hard young Therefore brother Sergey help herSergey give Nastya word t want word p Nastya remove letter certain order order strictly specify permutation letter indice word t a1 we denote length word x x note remove letter index letter do not change for example tnastya a415326 removal follow sequence word nastya nastya nastya nastya nastya nastya nastyaSergey know permutation his goal stop sister point continue remove word p since Nastya like activity Sergey want stop late possible your task determine letter Nastya remove stop SergeyIt guarantee word p obtain remove letter word t
1graph
after fourth season Sherlock Moriary realize foolishness battle decide continue competition peaceful game Credit CardsRules game simple player bring favourite ndigit credit card then player digits write card if digit equal player digit small get flick knock forehead usually forefing player for example n3 Sherlocks card 123 Moriartys card number 321 Sherlock name 1 Moriarty name 3 sherlock get flick then digit 2 get flick Finally Sherlock name 3 Moriarty name 1 get flickOf course Sherlock play honestly name digit order give Moriary true villain plan cheat he go digits order going change overall number occurence digit for example case Moriarty 1 2 3 flick 2 3 1 sherlock flicksYour goal find minimum possible number flick Moriarty like flick maximum possible number flick Sherlock Moriarty Note goal different optimal result obtain different strategy
2string
sherlock find piece encrypt datum think useful catch Moriarty the encrypted data consist integer l r he notice integer hexadecimal formHe take integer l r perform follow operation he list distinct digit present give number for example 101416 list digit 104 then sum respective power digit list step like example sum2120241910 he change initial number apply bitwise xor initial number sum Example note xor binary notation one example integer 1e sum sum21214 Letters b c d e f denote hexadecimal digit 10 11 12 13 14 15 respertivelysherlock want count number range l r inclusive decrease application step he want answer q query different l r
1graph
the Holmes child fight cleverestMycroft ask Sherlock Eurus find value fn f11 n2 fn number distinct order positive integer pair xy satisfy xyn gcdxy1 the integer gcdab great common divisor bSherlock say solve child play ask Mycroft instead value Summation positive integer d divide nEurus quietly observe finally come problem astonish Sherlock MycroftShe define kcomposite function Fkn recursively followsshe want tell value Fkn modulo 1000000007
1graph
Stepan like repeat vowel letter write word for example instead word pobeda write pobeeeedaaaaaSergey like behavior want write program format word write Stepan this program combine consecutive equal vowel single vowel the vowel letter e o u yThere exception letter e o repeat row exactly 2 time like word foot foot program skip transform vowel for example word iiiimpleeemeentatiioon convert word implemeentatioonsergey busy ask help write require program
1graph
stepan favorite string s consist lowercase letter latin alphabet after graduation decided remember long time ago can not remember but Stepan remember information string sequence integer c1c2cn n equal length string s ci equal number substring string s length consist letter the substre sequence consecutive character stre sFor example Stepans favorite string equal tttesst sequence c look like c7310000Stepan ask help repair favorite string s accord give sequence c1c2cn
2string
stepan n pen every day use ith day use pen number on n1th day use pen number 1 n2th use pen number 2 onon work day Monday Saturday inclusive Stepan spend exactly 1 milliliter ink pen use day on Sunday Stepan day rest stend ink pen use day Stepan know current volume ink pen now Monday morning Stepan going use pen number 1 today your task determine pen run ink rest ink leave Stepan use pen accord condition describe
2string
test datum generation easy task often generate big random test case ensure thorough testing solution correctnessfor example consider problem old Codeforces round its input format look roughly followsThe line contain single integer n 1nmaxn size set the second line contain n distinct integer a1a2an 1aimaxa element set increase orderif do not pay attention problem solution look fairly easy generate good test case problem let nmaxn random distinct ai 1 maxa sort soon understand easyhere actual problem solution Let g great common divisor a1a2an let xangn then correct solution output Alice x odd Bob x evenconsider wrong solution problem differ correct formula calculate xThe wrong solution calculate x xang subtract nThe second wrong solution calculate x xann divide ga test case interesting make wrong solution output incorrect answerGiven maxn maxa q find number interesting test case satisfy constraint output modulo q
1graph
Bearland big square plane it contain point coordinate exceed 106 absolute valueThere n house Bearland the ith locate point xiyi the n point distinct subset collinearBear Limak live house he want destroy house build new BearlandBears do not like big change for point house pi pj pk sign cross product pjpipkpi relocation if negativepositivezero negativepositivezero respectively this condition satisfy triple index ijk possibly equal different 1 additionally Limak is not allow build house point house exist point old house wasin formula define difference cross product point axay bxby axaybxbyaxbxayby axaybxbyaxbyaybxconsider set possible new placement Limaks house your task find area set pointsformally let Limak choose new placement randomly coordinate choose independently uniformly random interval 106106 let p denote probability getting allow placement new house Let S denote area Bearland S41012 your task find pS
1graph
Bear Limak examine social network its main functionality member friend talk share funny picturesthere n member number 1 n m pair member friend of course member can not friend themselvesLet ab denote member A b friend Limak think network reasonable follow condition satisfied for distinct member X Y Z XY YZ XZFor example Alan Bob friend Bob Ciri friend Alan Ciri friend wellcan help Limak check network reasonable Print yes no accordingly quote
1graph
a sequence square bracket regular insert symbol 1 regular mathematical expression for example sequence regular time irregular Draw give sequence minimalistic pseudographics strip low possible height use symbol for example sequence represent each bracket represent hepl symbols vertical symbol example give abovebrackets draw space divide pair consecutive pairwise bracket singlespace bar bracket visually merge symbol the image minimum possible height the enclosed bracket small surround bracket bracket separately strive maximize height image so pair final bracket example occupy entire height imagestudy carefully example adequately explain condition problem pay attention problem answer image unique
1graph
night gather watch begin it shall end death I shall wife hold land father child I shall wear crown win glory I shall live die post I sword darkness I watch wall I shield guard realm man I pledge life honor Nights Watch night night come the Nights Watch oathWith begin watch Jon Snow he assign task support stewardsthis time n steward provide support each steward strength Jon Snow like support steward exist steward strength strictly steward strength strictly great himcan find steward Jon support
1graph
Artsem vacation want buy souvenir teammate there n souvenir shop street in ith shop Artsem buy souvenir ai dollar buy souvenir shop he do not want introduce envy team want buy souvenir possible difference priceArtsem visit shopping street m time for strange reason ith day shop numbers li ri operate weird yes try come reasonable legend range query problem for visit Artsem wants know minimum possible difference price different souvenir buy open shopsIn word Artsems visit find minimum possible value asat listri st
0array
Comrade Dujikov busy choose artist Timofeys birthday recieving call Taymyr IliaalpinistIliaalpinist call n minute ie minute n 2n 3n artist come comrade m minute ie minute m 2 m 3 m the day z minute long ie day consist minute 12z how artist kill artist room Ilia call consider talk artist exactly minute
2string
you give tree connect undirected acyclic graph S TCount number subtree connect subgraph S isomorphic tree t since number large output modulo 1097two subtree tree S consider different exist vertex S belong exactly themtree g call isomorphic tree h exist bijection f set vertex g set vertex h follow property edge vertex a b tree g edge vertex fA fb tree h and vice versa edge vertex a b tree h edge f1a f1b tree g
1graph
you give string b you remove minimum possible number consecutive standing character string b way subsequence stre it happen need remove character maybe remove character b emptysubsequence string s string obtain erase zero character necessarily consecutive string s
1graph
Dasha decide rest solve problem D begin look photo previous competitionslet photo matrix size nm consists lowercase English lettersSome k photo especially interested receive phototemplate paint rectangular area certain color Lets photo special more formally ith special photo receive phototemplate replace character rectangle upper left corner cell coordinate aibi low right corner cell coordinate cidi symbol eiDasha ask find special photo total distance special photo minimum and calculate distancedetermine distance photo sum distance correspond letter the distance letter difference module position alphabet for example distance letter h m equal 8135 letter h 8th alphabet letter m 13th
2string
Dasha decide rest solve problem she ready start favourite activity origami remember puzzle solve the tree nonoriente connect graph cycle in particular n1 edge tree n verticesThe puzzle position vertex point cartesian plane integral coordinate segment vertice connected edge parallel coordinate axis also intersection segment allow end distinct vertex place different point help Dasha find suitable way position tree vertice planeIt guarantee possible position tree vertex plane violating condition give point integral coordinate do not exceed 1018 absolute value
1graph
on way programming school tiger Dasha face test huge staircase the step number infinity as know tiger fond stripe thing possible color so interval way calculate value number step odd number you need check interval step lth rth 1lr value Dasha find correct
1graph
alexander learning convert number decimal system do not know english letter write number decimal number mean instead letter a write number 10 thus convert number 475 decimal hexadecimal system get 11311 47511621316111160 Alexander live calmly try convert number decimal number systemalexander remember work little number ask find minimum decimal number convert system base n number k
2string
nothing eternal world Kostya understand 7th January see partially dead fourcolor garlandnow goal replace dead light bulb do not know light bulbs color require it guarantee color light workingIt know garland contain light bulbs color red blue yellow green the garland follow consecutive light bulb light bulbs color for example garland look like RYBGRYBGRY YBGRYBGRYBG BGRYB look like BGRYG ybgrybygr BGYBGY Letters denote color r red B blue Y yellow G greenuse information color light bulb work count number dead light bulb color
1graph
Bash get tired journey great Pokemon master so decide break play functionsbash define function f0n denote number way factoring n factor p q gcdpq1 in word f0n number order pair positive integer pq pqn gcdpq1but Bash feel easy calculate function so define series function fr1 define aswhere uv order pair positive integer need coprimenow Bash want know value frn different r n since value huge like know value modulo 1097 help
2string
its time year Felicity corner people celebrate himalayan region the Himalayan region n gym the ith gym gi Pokemon there m distinct Pokemon type Himalayan region number 1 m there special evolution camp set f claim evolve Pokemon the type Pokemon change evolve subject constraint Pokemon type evolving type evolve also Pokemon different type evolve different type evolve it possible Pokemon type evolve Formally evolution plan permutation f 12 m fxy mean Pokemon type x evolve Pokemon type yThe gym leader intrigue special evolution camp plan evolve pokemon the protocol mountain state gym type Pokemon number Pokemon type evolve Pokemon equal number Pokemon type evolve pokemon accord evolution plan they want find distinct evolution plan exist satisfy protocolTwo evolution plan f1 f2 distinct Pokemon type evolve different Pokemon type plan e exist f1if2iyour task find distinct evolution plan possible Pokemon gym evolve number Pokemon type gym remain as answer large output modulo 1097
1graph
Bash want Pokemon master day although like lot Pokemon fascinated Bulbasaur Soon thing start get fascination turn obsession since young catch Bulbasaur come way catch BulbasaurEach day take page newspaper he cut letter time page newspaper form word Bulbasaur quote stick wall Bash particular case letter Bulbasaur upper case rest low case by think catch Bulbasaur he repeat step leave newspaper he keep possible form word Bulbasaur newspapergiven text page newspaper tell Bulbasaurs catch todaynote uppercase lowercase letter consider different
1graph
PolandBall stand row many other ball more precisely exactly n Balls Balls proud home land want prove strongThe Balls decide start select exactly m group Balls consist single Ball neighboring Balls each Ball join groupThe Balls want impress Enemies they kindly ask calculate number division m 1mk output value modulo 998244353 enemy impress
1graph
PolandBall convex polygon n veritce diagonal intersect point PolandBall decide improve draw red segment he choose number k gcdnk1 Vertices polygon number 1 n clockwise way PolandBall repeat follow process n time start vertex 1 assume you ve end operation vertex x consider x1 operation draw new segment vertex x kth vertex clockwise direction this vertex xk xkn depend valid index polygon vertexyour task calculate number polygon section draw a section clear area inside polygon bound draw diagonal polygon side
2string
polandball play game enemyball the rule simple Players word turn you word say PolandBall start the Ball can not new word losesyoure give list word familiar polandball enemyball can determine win game play optimally
2string
one spring day way university Lesha find array a Lesha like split array part this time Lesha decide split array a possibly new array sum element new array zero one condition place new array form old array ALesha tired ask split array help Lesha
1graph
Limak go participate contest day 2016 the contest start 2000 hour exactly midnight there n problem sort difficulty ie problem 1 easy problem n hard Limak know 5i minute solve ith problemlimak friend organize New Years Eve party Limak want midnight early he need k minute house participate contest firstHow problem Limak solve want party
1graph
bachgold problem easy formulate give positive integer n represent sum maximum possible number prime number one prove representation exist integer great 1Recall integer k call prime great 1 exactly positive integer divisor 1 k
1graph
the country Treeland consist n city connect n1 bidirectional road way possible reach city start city road there soccer championship year participant Santa Clauses there exactly 2k team 2k different citiesduring stage team divide k pair team pair play game hometown team hometown team thus 2k city hold exactly soccer game however decide divide team pairsits necessary choose city settle player Organizers tend use city possible settle teamsNobody want travel championship team play city u v want live city short path u v maybe u v there constraint team pair live citysummarize organizer want divide 2k team pair settle minimum possible number city m way team pair live city lie hometown
1graph
eugeny n card exactly integer write Eugeny want exchange card nikolay number integer card equal number odd integer number distinct Nikolay m card distinct number 1 m write card it mean Nikolay exactly card number 1 exactly card number 2 a single exchange process Eugeny give card Nikolay take Nikolay your task find minimum number card exchange determine card eugeny exchange
1graph
Vladik bored way home decide play follow game he take n card row every card positive integer number exceed 8 write he decide find long subsequence card satisfie follow condition number occurrence number 1 8 subsequence do not differ 1 number occurrence number Formally ck card number k subsequence pair integer condition cicj1 hold card number x subsequence card number x subsequence form continuous segment necessarily continuous segment original sequence for example subsequence 1122 satisfie condition subsequence 1221 do not note 1122 do not satisfy condition please help Vladik find length long subsequence satisfie condition
0array
all know girl Arpas land ok you ve get idea DAnyone know Arpa is not normal man sorry I can not explain Mehrdad interested reason ask Sipa good biology scientist Arpas land help Sipa dna editor Sipa Arpa DNA editor dna editor show Arpas dna string S consist n lowercase english letter also Sipa dna T consist lowercase English letter belong normal manNow n1 option change Arpas DNA number 0 n ith T ith i1th character S 0 in if i0 T S SMehrdad wants choose interesting option Arpas DNA n1 option dna a interesting b a lexicographically small B Mehrdad ask Sipa q question give integer lrkxy interesting option consider option lir if interesting option Mehrdad want know small number iSince Sipa biology scientist programmer help
2string
little girl Alyona shop buy copybook school she study subject want equal number copybook subject there type copybook pack shop possible buy copybook ruble pack copybook b ruble pack copybook c ruble Alyona n copybookswhat minimum ruble pay buy number copybook k nk divisible 4 there infinitely pack type shop Alyona buy pack different type purchase
1graph
Alyona build n tower put small cube each cube size 111 a tower nonzero cube stand the tower form rowsometimes Alyona choose segment tower tower cube Formally Alyouna choose segment tower li ri add di cube themlet sequence a1a2an height tower leave right Lets segment tower alal1ar hill follow condition hold integer k lkr alal1al2akak1ak2arAfter addition di cubes tower li ri Alyona want know maximum width hill the width hill number tower
1graph
after celebration stack dirty plate Nikitas kitchen Nikita wash dryer in dryer plate place stack plate size increase the size plate distinctnikita free space specifically place stack plate therefore perform operation take number plate 1 dirty stack wash intermediate stack take number plate 1 b intermediate stack stack dryer Note perform operation plate order operationyou give size plate s1s2sn order dirty stack integer b all size distinct Write program determine Nikita plate increase order dryer if able program find sequence operation necessary optimal achieve
2string
Tanya friend gather celebrate birthday there n child celebration include TanyaThe celebration close end plan attraction gaming machine there m machine hall number 1 m each child list machine wants play Moreover machine know exact time want play for machine child play machine timeIt evening adult want home to speed process additionally rent second copy machine to rent second copy jth machine pay pj burle after rent machine use long wanthow long child play accord plan budget b burle rent additional machine there copy machine impossible rent machine typethe child interrupt game moment continue later if ith child wants play jth machine allow rent copy jth machine child play time jth machine time copy part the interruption change time perform integer moment time of course child can not play machine timeremember need save money save money expense child happiness need minimize late moment time child end game
1graph
Mr Funt live country specific tax law the total income mr Funt year equal n n2 burle tax pay calculate maximum divisor n equal n course for example n6 Funt pay 3 burle n25 need pay 5 n2 pay 1 burleAs mr Funt opportunistic person want cheat bit in particular want split initial n part n1n2nkn k arbitrary k1 allow pay taxis separately he can not equal 1 reveal so condition ni2 hold 1 kOstap Bender wonder money Funt pay ie minimal choose optimal way split n part
1graph
Anton grow tree garden in case forgot tree connect acyclic undirected graphThere n vertex tree paint black white Anton do not like multicolore tree want change tree vertex color black whiteTo change color Anton use operation type we denote paintv v vertex tree this operation change color vertex u vertice short path v u color include v u for example consider tree apply operation paint3 follow Anton interested minimum number operation need perform order color vertex equal
2string
Anton play interesting computer game stuck level to pass level prepare n potionsanton special kettle prepare potion x second also know spell type fast process prepare potion spell type speed preparation time potion there m spell type ith cost bi manapoint change preparation time potion ai instead x spell type immediately prepare number potion there k spell ith cost di manapoint instantly create ci potion Anton use spell type spell second type total number manapoint spend exceed s consider spell instantly right Anton start prepare potionsAnton want level fast possible interested minimum number time need spend order prepare n potion
1graph