question
stringlengths
58
4.29k
label
class label
3 classes
the array n integer give Lets sequence consecutive element segment also let segment kgood contain k different valuesFind long kgood segmentAs inputoutput reach huge size recommend use fast inputoutput method example prefer use scanfprintf instead cincout c prefer use bufferedreaderprintwrit instead ScannerSystemout Java
1graph
Jack decide invite Emma dinner Jack modest student do not want expensive restaurant Emma girl high taste prefer elite placesMunhattan consist n street m avenue there exactly restaurant intersection street avenue the street number integer 1 n avenue number integer 1 m the cost dinner restaurant intersection ith street jth avenue cijJack Emma decide choose restaurant follow way Firstly Emma choose street dinner Jack choose avenue Emma Jack make choice optimally Emma want maximize cost dinner Jack want minimize Emma take account Jack want minimize cost dinner find cost dinner couple love
1graph
its year 4527 tank game know love exist there exist Great Genas code write 2016 the problem code solve give number tank battle country find product if turn large server time assign tank team game collapsethere exactly n distinct country world ith country add ai tank game as developer game perfectionist number tank country beautiful a beautiful number accord developer number decimal representation consist digits 1 0 contain digit 1 however complaint player number tank country remove game number tank country remain beautifulYour task write program solve exactly problem order verify Genas code correctness just case
1graph
meanwhile kingdom K get ready marriage king daughter however order lose face relative King finish reform kingdom as King wait daughter marriage reform finish soon possiblethe kingdom currently consist n city city connect n1 bidirectional road city city as King save lot path citieswhat point reform the key ministry state relocate distinct city city important however fact high risk attack barbarians carefully the King plan describe set important city wonder good planBarbarians capture city important important one protection sure capture city impassable in particular interesting feature plan minimum number city barbarian need capture order important city isolate important city impossible reach important cityhelp King calculate characteristic plan
2string
Lesha play recently publish new version legendary game hacknet in version character skill mechanism introduce now player character exactly n skill each skill represent nonnegative integer ai current skill level all skill maximum level AAlong skill global rank player add Players rank accord socalled Force the Force player sum follow value the number skill character perfect ie aiA multiplied coefficient cf the minimum skill level skill min ai multiplied coefficient cm now Lesha m hacknetian currency unit willing spend each currency unit increase current level skill 1 equal a help spend money order achieve maximum possible value force
2string
hdd hard drive group data sector all file split fragment write sector hard drive note fragment write sector arbitrary orderone problem hdd hard drive follow magnetic head sector read filefind time need read file split n fragment the ith sector contain fith fragment file 1fin note different sector contain different fragment at start magnetic head position contain fragment the file reading follow manner fragment read magnetic head move sector contain second fragment second fragment read nth fragment read the fragment read order nthIt take ab time unit magnetic head sector sector b read fragment take time
1graph
Vika infinite sheet square paper Initially square white she introduce twodimensional coordinate system sheet draw n black horizontal vertical segment parallel coordinate axis all segment width equal 1 square mean segment occupy set neighbouring square situate row columnYour task calculate number paint cell if cell paint calculate exactly
1graph
connected undirected weight graph selfloop multiple edge give Graph contain n vertex m edgesfor edge uv find minimal possible weight span tree contain edge uvThe weight span tree sum weight edge include span tree
1graph
Nura want buy k gadget she s burle she buy gadget dollar pound so gadget selling type currency the type currency cost currency changingNura buy gadget n day for day know exchange rate dollar pound know cost conversion burle dollar poundseach day 1 n Nura buy gadget current exchange rate each day buy gadget want gadget buy n dayshelp Nura find minimum day index k gadgets Nura pay burle convert accord exchange rate purchase day Nura can not buy dollar pound store burle Gadgets number integer 1 m order appear input
1graph
you play board card game in game player characteristics x y white magic skill black magic skill respectively there n spell card lie table characteristic ai bi ci di in player pick card cast spell write characteristic meet requirement aix biy ie player magic skill cast spell however cast spell characteristics player change equal xci ydiAt begin game characteristic player equal zero the goal game cast nth spell your task move possible you allow use spell order number times example use spell
1graph
after see all your BASE ARE BELONG to US meme time number X Y realise different basis complicate relationsyoure give number x represent base bx number Y represent base Compare number
0array
you give rooted tree root vertex 1 each vertex colour colourlet colour c dominate subtree vertex v colour appear subtree vertex v time colour c so possible colour dominate subtree vertexthe subtree vertex v vertex v vertex contain vertex v path rootFor vertex v find sum dominate colours subtree vertex v
2string
Spongebob tired try reason weird action calculation simply ask find pair n m exactly x distinct square table consist n row m column for example 35 table 15 square 8 square 3 square the total number distinct square 35 table 158326
1graph
today Patrick wait visit friend Spongebob to prepare visit Patrick need buy goody store locate near house there d1 meter long road house shop d2 meter long road house second shop also road length d3 directly connect shop help Patrick calculate minimum distance need walk order shop return house Patrick start house he visit shop move exist road return house he do not mind visit shop pass road multiple time the goal minimize total distance travel
1graph
Igor museum want picture possibleMuseum represent rectangular field nm cell each cell impassable empty cell mark impassable cell mark every adjacent cell different type impassable divide wall contain pictureAt begin Igor cell at moment cell share current onefor start position calculate maximum number picture Igor Igor able picture cell adjacent wall picture Igor lot time examine picture
2string
you give set vector plane start origin your task find pair vector minimal nonoriente angle themnonoriente angle nonnegative value minimal clockwise counterclockwise direction angle Nonoriented angle 0 π for example opposite direction vector angle equal π
1graph
a restaurant receive n order rental each rental order reserve restaurant continuous period time ith order characterize time value start time li finish time ri lirirestaurant management accept reject order what maximal number order restaurant acceptNo accept order intersect ie can not share moment time if order end moment start can not accept
1graph
wilbur pig tinker array he array a1a2an initially consist n zero at step choose index add 1 element aiai1 subtract 1 element aiai1an his goal end array b1b2bn of course Wilbur want achieve goal minimum number step ask compute value
2string
Pasha recently buy new phone jPager start add friend phone number each phone number consist exactly n digitsalso Pasha number k sequence length nk n divisible k a1a2ank b1b2bnk Lets split phone number block length k the block form digits phone number position 1 2 k second block form digits phone number position k1 k2 2k Pasha consider phone number good ith block do not start digit bi divisible ai represent integer to represent block length k integer let write sequence c1 c2ck then integer calculate result expression c110k1c210k2ckPasha ask calculate number good phone number length n give k ai bi as number big print modulo 1097
1graph
Edo get collection n refrigerator magnetsHe decide buy refrigerator hang magnet door the shop refrigerator size door meet follow restriction refrigerator door rectangle length width door positive integersEdo figure want place magnet refrigerator he introduce system coordinate plane magnet represent rectangle side parallel coordinate axesnow want remove k magnet choose attach remain magnet refrigerator door area door small possible a magnet consider attach refrigerator door center lie door boundary the relative position remain magnet correspond planlet explain sentence let suppose want hang magnet refrigerator if magnet plan coordinate lower left corner x1 y1 upper right corner x2 y2 center locate integer by say relative position correspond plan mean available operation translation ie vector connect center magnet original plan equal vector connect center magnet refrigeratorthe side refrigerator door parallel coordinate axis
2string
in official contest problem different statement jury solution work incorrectly reason exclude contest this mistake fix current give problem statement model solution correspond jury want contestVova Lesha friend they meet Vovas place compete computer game name the Ancient Papyri Swordsink Vova choose warrior fighter Leshac choose archer after choose initial position character start fight a warrior good melee combat Vova try distance fighter small possible an archer prefer enemy distance Lesha try initial distance large possibleThere n n possible start position character mark Ox axis the position give distinct coordinate x1x2xn character end positionVova Lesha turn ban available position Vova move during turn guy ban exactly remain position ban position Vova Lesha they continue move possible position remain total number move n2 after Vovas character take position less coordinate Leshas character take position big coordinate guy start fightingVova Lesha tired game choosing position need play fight ask developer the Ancient Papyri Swordsink write module automatically determine distance warrior archer start fight Vova Lesha play optimally
1graph
bogdan birthday today mom give tree consist n vertecie for edge tree number xi write in case forget tree connect nondirected graph cycle after present grant m guest consecutively come Bogdans party when ith guest come perform exactly possible operation Chooses number yi vertecie ai bi after move edge tree vertex ai vertex bi short path course path unique tree every time move edge j replace current number yi result integer division yi div xj Chooses edge pi replace value write xpi positive integer cixpi as Bogdan care guest decide ease process Write program perform operation request guest output result value yi type
1graph
ari monster wake early ray sun thing feed squirrelAri draw regular convex polygon floor number vertice 12n clockwise order then start vertex 1 draw ray direction vertex the ray stop reach vertex intersect ray draw Ari repeat process vertex 23n particular order and put walnut region inside polygon Ada squirrel wants collect walnut allow step line draw Ari that mean Ada perform small jump want region Ada jump region p region Q P Q share cornerassume Ada start outside picture minimum number jump perform order collect walnut
1graph
Harry Potter HeWhoMustNotBeNamed engage fight death this time locate opposite end corridor length l two opponent simultaneously charge deadly spell enemy we know impulse Harrys magic spell fly speed p meter second impulse YouKnowWhos magic spell fly speed q meter secondthe impulse move corridor time collision turn round fly cast change original speed then soon impulse get caster wizard reflect send enemy change original speed impulseSince Harry perfectly master basic magic know second collision impulse disappear powerful explosion occur exactly place collision however young wizard is not good math ask calculate distance position place second meeting spell impulse provide opponent change position fight
2string
a topsecret military base command Colonel Zuev expect inspection Ministry Defence According charter topsecret military base include topsecret troop tell exactly secret troop end the problem Zuevs base miss topsecret troop reasonsThe colonel decide deal problem immediately order line single line n soldier base entrust Zuev know loquacity ith soldier leave equal qi Zuev want form topsecret troop k leftmost soldier line want total loquacity small possible troop remain topsecret to achieve go choose pair consecutive soldier swap he intend s time Note soldier participant swap number time the problem turn unusual colonel Zuev ask helpdetermine minimum total loquacity k soldier line achieve perform s swap consecutive soldier
2string
Duff mad friend that s make malek candy friend reason she n friend her ith friend si name necessarily unique q time ask malek candy friend she s angry act rule when wants ask Malek candy friend like k choose number l r tell Malek exactly candy himher occurt number occurrence string t sMalek able calculate candy request Duff that s ask help please tell candy request
1graph
Alice Bob decide eat fruit in kitchen find large bag orange apple Alice immediately take orange Bob take apple to process share remain fruit fun friend decide play game they multiple card write letter a letter B then begin remove card leave right time remove card letter A Alice give Bob fruit moment take bag apple orange thus number orange apple Alice change if card write letter B Bob give Alice fruit take bag set fruit after card way remove fruit bag overyou know orange apple bag your task find sequence card Alice Bob play
1graph
Marina love string length Vasya love stre different exactly t character help Vasya find stringmore formally give string s1 s2 length n number t Lets denote fab number character string b different then task find string s3 length n fs1s3fs2s3 t if stre print 1
1graph
Kolya love put gnome circle table give coin Tanya love study triplet gnome sit vertex equilateral trianglemore formally 3n gnome sit circle each gnome 1 3 coin Lets number place order occur circle number 0 3n1 let gnome sit ith place ai coin if integer 0 in aiainai2n6 Tanya satisfy Count number way choose ai Tanya satisfied as way distribute coin print remainder number modulo 1097 two way b consider distinct index 0i3n aibi gnome get different number coin way
1graph
one day Vasya Hipster decide count sock it turn red sock b blue socksaccorde late fashion hipster wear sock different color red left foot blue right footEvery day Vasya put new sock morning throw away go bed do not want wash themVasya wonder maximum number day dress fashionable wear different sock day wear sock run sock single pair sock he s gotcan help
1graph
you give n number a1a2an you perform k operation for operation multiply number x we want large possible denote bitwise or find maximum possible value perform k operation optimally
0array
a tree size n undirected connected graph consist n vertex cyclesconsider tree n vertex we tree invariant relative permutation pp1p2 pn vertex tree u v condition hold vertex u v connect edge vertex pu pv connect edgeyou give permutation p size n find tree size n invariant relative give permutation
2string
its riot time football stadium Ramacana Raging fan enter field police find difficult situation the field represent square coordinate system define diagonal vertex 00 105 105 the side square consider inside field outsideIn begin N fan field for fan give speed integer vi integer coordinate xi yi a fan coordinate second point xip yiq 0pqvi p q integerspoint outside square represent field exclude equal probability location specific fan secondAndrej young promising police officer send fly drone photo riot the drone camera work like it select point integer coordinate chance fan appear second they collinear camera will not work it guarantee initial position fan line Camera focus point create circle pass point a photo take second second initial state everything circle inside moment take photo second focus point photo your goal select point expect number fan see photo maximize if selection select point circle large radius if suitable selection accept if answer follow condition radius circle return small optimal 001 output consider correctNo test optimal radius big 1010
1graph
Ruritania country badly maintain road network exactly good news lorry driver constantly deliverie in fact road maintain oneway it turn impossible town legal way know town reachable illegallyfortunately police tend corrupt allow lorry driver break rule drive wrong direction provide receive small gift there patrol car road request 1000 ruritanian dinar driver drive wrong direction however greedy time patrol car notice driver break rule charge double money request previous time particular roadBorna lorry driver manage figure bribe pattern as job K stop town Ruritania stop certain order there n town enumerate 1 N Ruritania Bornas initial location capital city ie town 1 he happen know one n1 road Ruritania currently unidirectional unable compute money need prepare bribe police help Borna provide answer richly reward
1graph
Limak grizzly bear desire power adoration he want win upcoming election rule BearlandThere n candidate include Limak we know citizen go vote candidate now ith candidate ai vote Limak candidate number 1 to win election strictly vote candidatevictory important Limak decide cheat he steal vote opponent bribe citizen to bribe citizen Limak candy citizen bear bear like candy Limak do not candy wonder citizen bribe
2string
Limak old brown bear he go bowling friend today feel good try beat recordFor roll ball get score integer maybe negative number point Score ith roll multiply score sum so k roll score s1s2sk total score total score 0 rollsLimak n roll get score ai ith he want maximize total score come interesting idea he cancel roll say distract strong windLimak able cancel number roll maybe total score calculate noncanceled roll look sample test clarification what maximum total score Limak
1graph
Limak old brown bear he play poker friend today go casino there n player include Limak right bid table ith bid size ai dollarsEach player double bid number time triple bid number time the casino great jackpot making bid equal Is possible Limak friend win jackpot
1graph
in boolean logic formula conjunctive normal form CNF clausal normal form conjunction clause clause disjunction literal cite httpsenwikipediaorgwikiconjunctive_normal_formin word CNF formula type represent logical and conjunction represent logical or disjunction vij boolean variable negation each statement bracket call clause vij call literalsyou give CNF contain variable x1xm negation we know variable occur clause negation negation total your task determine CNF satisfiable value variable CNF value true if CNF satisfiable need determine value variable CNF true it guarantee variable occur clause
2string
you give stick positive integer length ab c centimeter you increase length positive integer number centimeter different stick increase different length total l centimeter in particular allow increase length stickdetermine number way increase length stick form nondegenerate have positive area triangle two way consider different length stick increase different number centimeter
1graph
one day Misha Andrew play simple game First player choose integer range 1 n Lets assume Misha choose number m Andrew choose number aThen random generator choose random integer c range 1 n integer 1 n choose probability winner player number close c the boy agree m locate distance c Misha winsandrew want win ask help you know number select Misha number n you need determine value Andrew choose probability victory high possiblemore formally need find integer 1an probability maximal c equiprobably choose integer 1 n inclusive
2string
company lot equipment furniture thing all track to inventory number assign item it easier create database number track everythingduring audit surprise find item number sequentially item share inventory number there urgent need fix you choose number item sequential start 1 change number timeconsume process like maximum use current numberingyou give information current inventory number n item company Renumber item inventory number form permutation number 1 n change number item possible let remind set n number form permutation number range 1 n number equal
1graph
note memory limit problem usuallet consider array consist positive integer position contain gapsWe collection number fill gap each number give collection onceyour task determine way fill gap long increase subsequence form array maximum size
1graph
Alice Bob love play onedimensional battle ship they play field form line consist n square cell 1n tableAt beginning game Alice put k ship field tell position Bob each ship look 1a rectangle occupy sequence consecutive square field the ship intersect touch otherafter Bob make sequence shot he name cell field Alice say cell miss cell belong ship hitbut here problem Alice like cheat may respond Bobs miss Help Bob catch Alice cheat find Bobs sure Alice cheat
1graph
all city Lineland locate Ox coordinate axis Thus city associate position xi coordinate Ox axis no city locate single pointlineland resident love send letter a person send letter recipient live city live city easy drop instrange true cost sending letter exactly equal distance sender city recipient cityFor city calculate value mini maxi mini minimum cost sending letter ith city city maxi maximum cost sending letter ith city city
2string
as know maximum clique problem arbitrary graph NPhard Nevertheless graph specific kind solve effectivelyjust case let remind clique nondirected graph subset vertex graph vertex subset connect edge in particular set vertex set consist single vertex cliqueslet define divisibility graph set positive integer Aa1a2an follow the vertex give graph number set a number ai aj ij connected edge ai divisible aj aj divisible aiYou given set nonnegative integer a Determine size maximum clique divisibility graph set a
2string
Gerald buy rare painting Sothebys auction wants hang wall for buy special board attach wall place painting board the board shape a1b1 rectangle painting shape a2b2 a3b3 rectanglesSince painting paint style abstract art matter exactly rotate board painting parallel floor the painting touch edges board overlap edge board Gerald ask possible place painting board board buy large
1graph
Amr live Lala Land Lala Land beautiful country locate coordinate line Lala Land famous apple tree grow everywherelala land exactly n apple tree tree number locate position xi ai apple grow Amr want collect apple apple tree Amr currently stand x0 position at begin choose right leave Hell continue direction meet apple tree do not visit Hell apple reverse direction continue walk direction meet apple tree do not visit in word Amr reverse direction visit new apple tree Amr stop collect apple tree do not visit direction facingwhat maximum number apple collect
1graph
soon school Olympiad Informatics hold Berland n schoolchildren participate thereat meeting jury Olympiad decide n participant depend result diploma second degree Thus student receive exactly diplomathey decide give min1 max1 diplomas degree min2 max2 diplomas second degree min3 max3 diploma degreeafter discussion decide choose option distribute diploma satisfy limitation maximize number participant receive diplomas degree of option select maximize number participant receive diplomas second degree if multiple option select option maximize number diploma degreechoosing good option distribute certificate entrust Ilya good programmer Berland however find important thing task choose good option distribute diploma base describe limitationsIt guarantee describe limitation way choose option distribute diploma n participant Olympiad receive diploma degree
1graph
Andrewid Android galaxyfamous detective he investigate case fraud fake copy famous Stolps gear puzzle famous Rubiks cube wasits important component button line n similar gear each gear n tooth contain number 0 n1 counterclockwise order when push button gear rotate clockwise second gear rotate counterclockwise gear rotate clockwise onbeside gear exactly active tooth when gear turn new active tooth follow current active tooth accord direction rotation for example n5 active tooth contain number 0 clockwise rotation make tooth number 1 active counterclockwise rotate make tooth number 4 activeAndrewid remember real puzzle follow property push button multiple time way end number active tooth gear form sequence 012n1 write program determine give puzzle real fake
1graph
Vanya math homework he expression form x1x2xn digit 1 9 sign represent plus multiplication sign Vanya need add pair bracket expression maximize value result expression
1graph
you give nonnegative integer n decimal representation consist 100 digit do not contain lead zeroesYour task determine possible case remove digit possibly remove digit result contain digit form nonnegative integer do not lead zero divisible 8 after remove forbidden rearrange digitsif solution exist print
0array
the algorithm detect face image work realtime develop Paul Viola Michael Jones 2001 a algorithm procedure compute Haar feature as task consider simplify model conceptlet consider rectangular image represent table size nm the table element integer specify brightness pixel imageA feature rectangular table size nm each cell feature paint black whiteTo calculate value give feature give image perform follow step first table feature table image rotation reflection pixel entirely cover black white cell the value feature image value WB W total brightness pixel image cover white feature cell b total brightness pixel cover black feature cellssome example popular Haar feature give your task determine number operation require calculate feature socalled prefix rectanglesA prefix rectangle rectangle image upper leave corner coincide upper leave corner imageYou variable value value initially zero in operation count sum pixel value prefix rectangle multiply integer add variable valueyou give feature it necessary calculate minimum number operation require calculate value attribute arbitrary image for well understanding statement read explanation sample
2string
whatthefatherland strange country all phone number string consist lowercase english letter what double strange phone number associate bearsIn country rock band call CF consist n bear include Mike number 1 n phone number ith member CF si May 17th holiday name Phone call day in Phone Calls day call number substring hisher number number time in particular call strange countrydenote callij number time ith member CF call jth member CF the geek Mike q question want ask in question give number lr k tell number
1graph
Mike president country WhatTheFatherland there n bear live country Mike all standing line number 1 n leave right ith bear exactly ai foot high a group bear nonempty contiguous segment line the size group number bear group the strength group minimum height bear groupMike curious know x 1xn maximum strength group size x
1graph
two soldier play game at beginning choose positive integer n give second soldier then second try maximum possible number round each round consist choose positive integer x1 n divisible x replace n nx when n equal 1 possible valid move game score second soldier equal number round performedto game interesting soldier choose n form ab positive integer b ab here k denote factorial k define product positive integer large kWhat maximum possible score second soldier
2string
two bored soldier play card war their card deck consist exactly n card number 1 n value different they divide card manner possible different number card then play warlike card game the rule follow on turn fight happen each pick card stack put table the card value big win fight take card table stack more precisely take opponent card put stack put card stack if turn player stack lose win you calculate fight happen win game state game will not end
1graph
little girl Susie go shop mom wonder improve service quality there n people queue for person know time ti need serve a person disappoint time wait time need serve the time person wait total time people stand queue serve Susie think swap people queue decrease number people disappoint help Susie find maximum number disappoint people achieve swap people queue
1graph
you give stre q a sequence k strings s1s2sk call beautiful concatenation string stre q formally s1s2skq character string distinctfind beautiful sequence string determine beautiful sequence do not exist
2string
the country n city n1 bidirectional road possible city road the city number integer 1 n inclusiveall road initially bad government wants improve state road we assume citizen happy road improvement path capital locate city x city contain bad roadyour task possible x determine number way improve quality road order meet citizen condition as value large need print value modulo 1000000007 1097
1graph
polycarp make quest friend he n task task boy evaluate interesting integer qi time ti minute need complete task an interesting feature quest participant task well suit depend preference the task choose base interactive quiz consist question the player answer question yes depend answer question participant move question go task quest in word quest binary tree node contain question leave contain task we know answer question ask get task take exactly minute quest player Polycarp know friend busy people can not participate quest t minute Polycarp wants choose n task invent correspond set question use form interactive quiz binary tree matter player answer quiz question spend T minute complete quest answer question complete task specifically quest contain zero question straight task each task ie people different answer question different taskspolycarp want total interest value task involve quest large possible help determine maximum possible total interest value task consider quest complete T minute variant answering question
2string
its tough superhero and twice tough resist supervillain cool math suppose you re ordinary Batman ordinary city Gotham your enemy Joker mine build city administration minute neutralize charge to enter cancel code bomb control panelHowever mad man decide hint this morning mayor find playing card pillow there line write cardthe bomb note say JxA a positive integer you suspect cancel code integer x meet equation JxA now order decide neutralize bomb run life you ve get count distinct positive integer x meet equation
1graph
a duck hunter favorite thing hunt he live dimensional world locate point 00 as do not like walk prey prefer shoot vertically case duck fall straight hand the hunter do not reload gun immediately r second pass shot when hunter shoot bullet immediately hit duck directly hunterin dimensional world duck horizontal segment move horizontally negative direction Ox axis speed 1 length unit second for duck know value hi ti xcoordinate head leave end segment tail right end segment time 0 the height duck flying is not important gun shoot vertically infinite height hit duck way the figure sample what maximum number duck hunter shoot the duck consider shot hunter moment shot point intersect Oy axis after hunter shoot duck fall can not shot anymore the hunter shot moment time 0
1graph
t student apply ZPP class Summer Irrelevant School the organize committee school enroll number t student enrol the enrol student divide group manner possible group emptyduring shift student ZPP grade tutor n teacher due nature educational process teacher assign exactly group possible teacher assign group the ith teacher willing work group long group li ri student bore hard besides pair teacher do not like work group total m pair conflict teachersyou head teacher Summer Irrelevant School get difficult task determine student enroll group group teacher teach
1graph
Demiurges Shambambukli Mazukta love watch game ordinary people today notice man play follow gameThere root tree n node m leave leaf node child edge tree direct parent child in leave tree integer 1 m place way number appear exactly leafinitially root tree contain piece two player piece turn player move piece current node child player game end immediately the result game number place leaf piece complete movement the player make try maximize result game second player contrary try minimize result we assume player optimally welldemiurge omnipotent game arbitrarily rearrange number place leave Shambambukli want rearrange number result game player play optimally large possible Mazukta want result small possible what outcome game number rearrange Shambambukli number rearrange Mazukta of course demiurge choose good possible option arrange number
2string
a tourist hike mountain range the hike last n day day tourist note height sea level on ith day height equal integer hi the tourist pick smooth route hike mean consecutive day height change 1 ie 1 n1 inequality hihi11 holdsAt end route tourist raft mountain river note journal wash away Moreover number note distort now tourist wonder maximum height hike help restore maximum possible value maximum height hike determine note distort represent possible height value meet limit hihi11
2string
Tavas strange creature usually zzz come people mouth sleep string s length n come Tavas mouth instead Today Tavas fall asleep Malekas place while sleep Malekas little process s Malekas favorite string p he determine position x1x2xk p match s more formally xi 1ik condition sxisxi1 sxip1p fullfilledThen Malekas write subsequence x1x2 xk possibly do not write piece paper here sequence b subsequence sequence turn b remove element maybe allafter Tavas wake Malekas tell he could not remember string s know p s contain lowercase english letter subsequence write piece paperTavas wonder number possible value s he ask saddas was not smart solve so Tavas ask calculate number himanswer large Tavas want print answer modulo 1097
1graph
analyze mistake people type search query complex interesting work as guarantee way determine user originally mean type query use different sort heuristicspolycarp need write code give word check obtain word result typos Polycarpus suggest common typo skip exactly letter type wordimplement program give distinct word S T length n determine word w length n1 property transform W S t delete exactly character Words S t consist lowercase English letter Word W consist lowercase english letter
1graph
n variable x1xn positive integer value you give K constraint value look like value variable xi1xi2xim different among possible list value variable satisfy constraint select one minimum possible maxXi Output lexicographically list
1graph
you give set point plane positive integer coordinate find triangle minimum area vertex point 00 a0 0B A B unknown positive integer contain give point inside point edge count inside
1graph
Ford Prefect get job web developer small company make towel his current work task create search engine website company during development process need write subroutine compare string S T equal length similar after brief search internet learn Hamming distance string S T length define number position S t different character for example hamming distance word permanent pergament word differ fourth sixth lettersmoreover search information notice modern search engine powerful mechanism correct error request improve quality search Ford do not know human being assume common mistake request swap arbitrary letter stre necessarily adjacent now want write function determine letter swap string S Hamming distance new string S string T small possible determine replacement reduce distance stringshelp
1graph
Pasha get beautiful string s birthday string consist lowercase latin letter the letter string number 1 s left right s length give stringPasha do not like present decide change after birthday Pasha spend m day perform follow transformation stringeach day choose integer ai reverse piece string segment position ai position sai1 it guarantee 2aisyou face follow task determine Pashas string look like m day
0array
Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле В одной известной социальной сети дружба симметрична то есть если является другом b то b также является другом в этой же сети есть функция которая демонстрирует множество людей имеющих высокую вероятность быть знакомыми для пользователя Эта функция работает следующим образом Зафиксируем пользователя x Пусть некоторый другой человек y не являющийся другом x на текущий момент является другом не менее чем для k друзей x Тогда он является предполагаемым другом для xу каждого человека в социальной сети есть свой уникальный идентификатор это целое число от 1 до 109 Вам дан список пар пользователей являющихся друзьями Определите для каждого упомянутого пользователя множество его предполагаемых друзей
2string
polycarp fly airplane finally favorite time lunchtime the BerAvia company stewardess give food consecutively passenger 1th Polycarp sit seat m mean mth person foodthe flight menu k dish total Polycarp board flight time count number portion dish board thus know value a1a2ak ai number portion ith dishThe stewardess give food m1 passenger give Polycarp polite smile ask prefer that s Polycarp realize run dish moment for m1 passenger ahead notice dish give besides he s hear strange mumbling m1 passenger ahead similar phrase I m disappoint that happen passenger ask dish stewardess give polite smile say run dish in case passenger need choose dish available if Polycarp hear sound passenger mean passenger choose dish tryhelp polycarp find dish run dish moment Polyarp serve dish definitely available
1graph
you organize cycling race street city the city contain n junction pair connect road road direction no road connect pair intersection road connect intersection itselfyou want race open professional athlete beginner cyclist that s organize race nomination easy moderate difficult participant choose suitable nomination for nomination choose route chain junction consecutively connect road route meet follow condition route start intersection finish intersection place start finish can not avoid collision route common junction common start finish road irrespective drive direction road route route pass twice intersection visit road twice irrespective drive direction road second time visitprepare competition begin need determine route race quickly possible the length route important important give requirement meet
1graph
once Vasya Petya assemble figure m cube associate number 0 m1 inclusive number appear exactly Lets consider coordinate system ox ground OY direct upwards each cube associate coordinate low leave corner coordinate integer cubethe figure turn stable this mean cube ground cube cube touch corner more formally mean cube coordinate xy y0 cube coordinate x1y1 xy1 x1y1Now boy want disassemble figure cube row in step cube remove figure right block lay the guy remove cubes order figure remain stable to process interesting guy decide play follow game the guy cube figure turn it easy figure disassemble integer write cube form number write mary positional numerical system possibly lead zero Vasya want result number maximum possible Petya contrary try small possible Vasya start gameYour task determine number form figure disassemble boy play optimally determine remainder answer modulo 1099
2string
Vasya interested bioinformatic he s go write article similar cyclic DNA sequence invent new method determine similarity cyclic sequenceslet assume string s t length n function hst define number position respective symbol s t Function hst define function Vasya distance ρst obtain string s apply leave circular shift time for example ρagccgt hagccgthagcgtchagctcg hgcacgthgcagtchgcatcg hcagcgthcaggtchcagtcg 1100111016vasya find string s length n internet now want count string t Vasya distance string s attain maximum possible value formally speak t satisfy equation Vasya try possible string find answer need help as answer large count number string modulo 1097
1graph
a b prepare programming contestsafter year sport programming solve problem require calculate sort abstract object a B develop peculiar tastesA like lowercase letter latin alphabet he assign letter number show like letter assign negative number letter dislike b like substring he especially like one start end letter length exceed oneAlso A b string s now try find substring t string s interesting b t start end letter length large sum value letter assign a equal zeronaturally A b quickly find number substring t interesting can
1graph
after bracket sequence Arthur take number theory he get new favorite sequence length n a1a2an consist integer integer k exceed nThis sequence follow property write sum segment consist k consecutive element a1a2aka2a3ak1ank1ank2an number form strictly increase sequencefor example follow sample n5k3a12456 sequence number look follow 12424545671115 mean sequence meet describe property obviously sequence sum nk1 elementssomebody will not replace number arthur sequence question mark number replace replace exactly question mark we need restore sequence meet require property minimize sum ai ai absolute value ai
2string
Anya buy new smartphone use Berdroid operating system the smartphone menu exactly n application application icon the icon locate different screen screen contain k icon the icon kth locate screen k1th 2kth one second screen screen partially emptyinitially smartphone menu show screen number 1 to launch application icon locate screen t Anya need follow gesture scroll require screen number t make t1 gesture icon screen t gesture press icon require application exactly launch itafter application launch menu return screen that launch application need scroll menu start screen number 1all application number 1 n we know certain order icon application locate menu begin change long use operating system Berdroid intelligent system change order icon move frequently icon begin list formally right application launch Berdroid swap application icon icon precede application icon application position small order menu the precede icon possibly locate adjacent screen the exception icon launch application occupy place case icon arrangement do not changeAnya plan order launch application how gesture Anya launch application plan order note application launch multiple time
1graph
Drazil Varda earthworm couple they want find good place bring child they find good ground contain nature hole the hole contain room pair room connect small tunnel earthworm themlets consider room small tunnel vertex edge graph this graph tree in word pair vertex unique path themeach room leaf graph connect ground vertical tunnel here leaf vertex outgoing edge graphEach room large fit earthworm live Earthworm can not live tunnelDrazil Varda plan educate child they want child morning exercise immediately get upWhen morning come earthworm child time choose farth path ground gather child lazy want exercise late possibleDrazil Varda want difference time earthworm child arrive outside time earthworm child arrive outside large l child spread ground hard exercise togetheralso the room occupy child form connect set in word room occupy earthworm child room lie path occupy earthworm child toohow child Drazil Varda order satisfy condition Drazil Varda want know answer different choice lDrazil Varda do not live hole child
2string
Drazil create follow problem put 12 tile nm gridThere grid cell cell occupy you use 12 tile cover cell tile cover and print solution itBut Drazil do not like write special checking program task his friend Varda advise ask contestant print solution exist unique Otherwise contestant print not unique Drazil find constraint task large original taskcan solve new problemnote print not unique exist solution exist different solution original task
1graph
Drazil friend some happy unhappy Drazil want friend happy so invent follow planthere n boy m girl friend Lets number 0 n1 0 m1 separately in ith day Drazil invite th boy th girl dinner Drazil programmer start 0 if people happy happy Otherwise people remain state once person happy heshe happy originally stay happy foreverDrazil wants know use plan friend happy moment
1graph
you give permutation n number p1p2pn we perform k operation follow type choose uniformly random index l r lr reverse order element plpl1pr your task find expect value number inversion result permutation
1graph
Cthulhu decide catch Scaygerboss Scaygerboss find try hide pack scayger each scayger scaygerboss male female scaygerbosss gender otherscayger scatter twodimensional map divide cell a scayger look nerdy loveable staying cell exactly scayger gender different gender Cthulhu able catch Scaygerboss scayger map look nerdy loveablethe scayger different speed for scayger give time take scayger cell adjacent cell cell adjacent share common at point time cell contain obstacle occupy arbitrary number scayger Scaygers cell obstaclescalculate minimal time order scayger look nerdy loveable optimally goal
2string
you give array length n number k Lets pick k nonoverlapping nonempty subarray initial array let si sum ith subarray order leave right Compute maximum value follow expression s1s2s2s3sk1skHere subarray contiguous array
2string
you give permutation p number 12n Lets define fp follow sumfind lexicographically mth permutation length n set permutation have maximum possible value fp
1graph
Vasya array consist nonnegative integer size n b size m Vasya choose positive integer k create nm matrix v follow formulavasya write matrix v piece paper tableA year later Vasya cleaning table find piece paper contain nm matrix w he remember make matrix day rule give sure find paper matrix v day your task find matrix w you ve find obtain follow rule number ka1a2anb1b2bm possible
1graph
while dad work little girl Tanya decide play dad password secret database dad password string consist n2 character she write possible n threeletter continuous substring password piece paper piece paper throw password each threeletter substre write number time occur password Thus Tanya end n piece paperthen Tanya realize dad upset learn game decide restore password string correspond final set threeletter string you help difficult task we know dad password consist lowercase uppercase letter Latin alphabet digit Uppercase lowercase letter latin alphabet consider distinct
1graph
Anya love watch horror movie in good tradition horror visit m ghost tonight Anya lot candle prepare visit candle produce light exactly t second it take girl second light candle more formally Anya spend second light candle candle burn exactly t second go long usedFor m ghost Anya know time come ith visit happen wi second midnight wis distinct each visit last exactly secondwhat minimum number candle Anya use visit r candle burn Anya start light candle time integer number second midnight possibly time midnight that mean start light candle integer number second midnight integer number second midnight word integer moment time
1graph
Mr Kitayuta kindly give string s consist lowercase english letter you ask insert exactly lowercase english letter s palindrome a palindrome string read forward backward for example noon testset palindrome test kitayuta notYou choose lowercase english letter insert position s possibly begin end s you insert letter give stre palindromeif possible insert lowercase english letter s result string palindrome print string insertion Otherwise print NA quote casesensitive in case palindrome obtain allow print
1graph
New Year come Jaehyun decide read book 2015 unlike year he n book number integer 1 n the weight ith 1 in book wiAs Jaehyuns house large bookshelf keep n book stack vertically when wants read certain book x follow step describe he lift books book x he push book x stack he put lift book change order after read book x put book x stack he decide read book m day in jth 1jm day read book number integer bj 1bjn to read book use process describe paragraph it possible decide reread book timesafter make plan realize total weight book lift m day heavy so decide change order stack book New Year come minimize total weight you assume book stack possible order note book going read certain step is not consider lift step can help
0array
you write piece paper array n positive integer a1a2an m good pair integer i1j1i2j2imjm each good pair ikjk meet follow condition ikjk odd number 1ikjknin operation perform sequence action good pairs ikjk integer v v1 divide number aik ajk divide number v e perform assignment determine maximum number operation sequentially perform give array note pair time describe operation
2string
Petya Gena love play table tennis a single match play accord follow rule match consist multiple set set consist multiple serve each serve win player player score point as soon player score t point win set set start score player set 0 as soon player win total s set win match match here s t positive integer numbersTo spice Petya Gena choose new number s t match besides sake history record match serve write winner Serve winner record chronological order in record set soon player score t point match soon player win s setsPetya Gena find record old match unfortunately sequence serve record is not divide set number s t give match lose the player wonder value s t can determine possible option
1graph
Mike try rock climbing awful there n hold wall ith hold height ai grind besides let sequence ai increase aiai1 1 n1 sequence track Mike think track a1 difficulty in word difficulty equal maximum distance hold adjacent heightToday Mike decide cover track hold hang height a1 to problem hard Mike decide remove hold remove element sequence example sequence 12345 remove element obtain sequence 1245 however Mike awful climbing want final difficulty ie maximum difference height adjacent hold remove hold small possible possible option remove hold the hold stay positionshelp Mike determine minimum difficulty track remove hold
1graph
during 24 hour Hamed Malek spend time play Sharti now exhausted finish round so ask help determine winner round Sharti play nn board cell color white colored black the row board number number 1 n also column board number leave right number 1 n the cell locate intersection ith row jth column denote ijthe player alternatively turn in turn player choose square sidelength k lowerright cell paint white then color cell square inverse white cell black viceversa the player perform turn lose you know Hamed Malek clever play good move turn know fact Hamed take turn give initial board describe input determine winner
2string
Ali hamed little brother tomorrow birthday Hamed want brother earn gift give hard programming problem tell successfully solve hell brand new laptop Ali talented programmer like Hamed usually do not cheat time exception its brand new laptop so decide secretly seek help please solve problem Ali an nvertex weight rooted tree give Vertex number 1 root tree we define duv sum edge weight short path vertex u v specifically define duu0 also let define Sv vertex v set contain vertex u d1ud1vdvu Function fuv define follow formulaThe goal calculate fuv q give pair vertex as answer large print modulo 1097
1graph
Vasya study class school soon exam he decide study polynomial Polynomial function pxa0a1x1anxn Numbers ai call coefficient polynomial nonnegative integer n call degree polynomialvasya bet friend solve problem polynomial they suggest problem Determine polynomial Px exist integer nonnegative coefficient b give positive integer Vasya like lose bet idea solve task help solve problem
1graph
Vanya decide walk field size nn cell the field contain m apple tree ith apple tree cell coordinate xiyi Vanya move vector dxdy that mean Vanya cell xy second cell the following condition satisfy vector large integer divide b Vanya end path reach square visit Vanya wonder square field start path apple tree possible
2string
Vanya want pass n exam academic scholarship he scholarship average grade mark exam avg the exam grade exceed r Vanya pass exam get grade ai ith exam to increase grade ith exam 1 point Vanya write bi essay he raise exam grade multiple timeswhat minimum number essay Vanya need write scholarship
1graph
think New York rectangular grid consist N vertical avenue numerate 1 N M horizontal street numerate 1 M C friend stay c hotel locate streetavenue crossing they go celebrate birthday h restaurant locate streetavenue crossing they want maximum distance cover travel restaurant minimum possible help friend choose optimal restaurant celebrationsuppose distance neighboring crossing equal kilometer
2string