question
stringlengths
58
4.29k
label
class label
3 classes
you give string s consist n lowercase latin lettersYou remove ie zero character string way string obtain lexicographically small string obtain operationString s s_1 s_2 dot s_n lexicographically small string t t_1 t_2 dot t_m n m s_1 t_1 s_2 t_2 dots s_n t_n exist number p p le minn m s_1 t_1 s_2 t_2 dot s_p1 t_p1 s_p t_pfor example aaa small aaaa abb small abc pqr small z
2string
Palo Alto unusual city endless coordinate line it know office Lyft Level 5Lyft popular m taxi driver city day transport rest city resident n ridersEach resident include taxi driver PaloAlto live unique location pair resident coordinate sameThe Lyft system clever rider call taxi taxi driver close person if multiple one distance taxi driver small coordinate selectedbut morning taxi driver wonder rider give taxi driver order taxi day in word need find taxi driver number a_i number rider ith taxi driver driver rider homethe taxi driver transport taxi driver
1graph
you give integer l r l le r your task calculate sum number l r include l r number contain k different digit print sum modulo 998244353for example k 1 calculate number l r number form digit for l 10 r 50 answer 11 22 33 44 110
1graph
a lot people dream convertible call cabriolet some convertible do not roof vulnerable rain this Melon ask famous inventor decide create rain protection mechanism convertiblesthe workplace mechanism plane driver its functional consist rail slide endpoint piece stretch rope for sake simplicity consider pair parallel segment plane rope segment endpoint free choose point rail segment the algorithmic mechanism detect particular raindrop predict reach plane at exact moment rope segment contain raindrop point rope adsorb raindropyou give initial position rope endpoint information raindrop you choose minimal possible speed v endpoint slide endpoint slide direction segment independently way possible catch raindrop move endpoint speed great v find impossible matter high speed
2string
Berland n city connect road each road bidirectional connect distinct city city there s road connect themthe president Berland decide split country r state way city belong exactly r statesafter split road connect city state city different state Lets road connect city state inner roadsThe president do not like odd people odd city odd number wants split way city number inner road connect itPlease help president find small possible r split exist
1graph
polycarp work new operate system call BerOS he ask help implementation file suggestion featurethere n file hard drive name f_1 f_2 dot f_n any file contain 1 8 character inclusive all file name uniquethe file suggestion feature handle query represent string s for query s count number file contain s substre ie continuous segment character file equal s suggest file nameFor example file name readme host op beros18 query os number match file 2 file name contain os substre suggest file host beros18
2string
Elections Berland come there candidate Alice BobThe main Berland TV channel plan political debate there n people want debate spectator each person describe influence political view there kind political view support candidate kind denote 00 support Alice Bob kind denote 10 support Bob Alice kind denote 01 support candidate kind denote 11 the direction tv channel wants invite people debate the set invite spectator satisfy condition half spectator support Alice ie 2 cdot ge m number spectator support Alice m total number spectator half spectator support Bob ie 2 cdot b ge m b number spectator support Bob m total number spectator total influence spectator maximal possible help tv channel direction select nonempty set spectator tell impossible
1graph
Enough Too time happen Vasya forgot dispose garbage apartment stank now want create garbage disposal plan stick itFor n day Vasya know a_i number unit garbage produce ith day each unit garbage dispose day produce day Vasya dispose garbage put inside bag drop bag garbage container each bag contain k unit garbage it allow compose drop multiple bag garbage container single daybeing economical Vasya want use bag possible you compute minimum number bag Vasya need dispose garbage give n day no garbage leave nth day
1graph
let define rank undirected graph rank adjacency matrix mathbbRn time ngiven tree each edge tree delete probability 12 deletion independent Let E expect rank result forest Find e cdot 2n1 modulo 998244353 easy e cdot 2n1 integer
1graph
someone strange birthday present Ivan it hedgehog connect undirected graph vertex degree 3 center vertex degree 1 Ivan think hedgehog boring decide kmultihedgehogLet define kmultihedgehog follow 1multihedgehog hedgehog vertex degree 3 vertex degree 1 for k ge 2 kmultihedgehog k1multihedgehog follow change vertex v degree 1 let u neighbor remove vertex v create new hedgehog center vertex w connect vertex u w edge new hedgehog differ initial gift Thereby kmultihedgehog tree Ivan kmultihedgehog sure mistake that ask check tree kmultihedgehog
2string
Maksim walk cartesian plane initially stand point 0 0 adjacent point leave right for example Maksim currently point 0 0 follow point 1 0 0 1 1 0 0 1 there n distinct key point plane the ith point p_i x_i y_i it guarantee 0 le x_i 0 le y_i key point 0 0let level point point maxx_i y_i 1 second level point point maxx_i y_i 2 Maksim want visit key point but should not visit point level 1 visit point level he start visit point minimum level point give setthe distance point x_1 y_1 x_2 y_2 x_1 x_2 y_1 y_2 v absolute value vMaksim wants visit key point way total distance walk minimum possible your task find distanceif Python programmer consider PyPy instead Python submit code
2string
let denote sequence Fibonacci stringsf0 0 f1 1 Fi Fi 2 fi 1 plus sign denote concatenation stringslet denote lexicographically sort sequence suffix stre fi AFi for example F4 01101 AF4 follow sequence 01 01101 1 101 1101 Elements sequence number 1your task print m character kth element AFn if m character suffix output suffix
1graph
at childrens festival child dancing circle when music stop play child stand circle then Lena remember parent give candy box exactly k candy WilkyMay Lena greedy person decide present candy friend circle Lena know friend sweet tooth Sweet tooth take box candy box candy take the rest lenas friend exactly candy boxbefore start candy Lena step circle exactly n people remain Lena numbered friend clockwise order positive integer start 1 way index 1 assign good friend RomaInitially Lena give box friend number l friend start friend number l take candies box pass box friend clockwise order the process end friend number r take candy know box please note possible lenas friend take candy box time box go circle emptylena know friend sweet tooth interested maximum possible number friend sweet tooth if situation happen Lena prove wrong observation tell
1graph
the company X n employee number 1 n each employee u direct boss p_u 1 le p_u le n employee 1 boss it guarantee value p_i form tree Employee u say charge employee v u direct boss v employee w w charge v u direct boss w also employee consider charge himselfIn addition employee u define level lvu follow lv10 lvulvp_u1 u neq 1 in near future q possible plan company operate the ith plan consist integer l_i r_i mean employee range l_i r_i involve plan to operate plan smoothly project manager employee charge involve employee to precise employee u choose project manager ith plan employee v l_i r_i u charge v note u necessary range l_i r_i also u choose way lvu large possible high level low salary company pay employeebefore plan operate company jatc look plan after glance tell company plan possible reduce number involve employee exactly affect plan Being greedy company ask jatc employee kick plan level project manager require large possible jatc figured answer challenge
1graph
you give positive integer n greater equal 2 for pair integer b 2 le b le n transform b exist integer x 1 x cdot x b b cdot x x denote absolute value xAfter transformation score increase x point allow transform b b anymoreinitially score 0 you start integer transform time like what maximum score achieve
1graph
you invite n guest dinner you plan arrange circle chair each chair go occupy guest you number circle your guest happen little bit shy ith guest want l_i free chair leave chair r_i free chair right the left right direction choose assume guest go seat center circle Note guest circle l_i chair leave r_i chair right overlapwhat small total number chair use
1graph
you successfully find poor Arkady near exit station you ve perfectly predict you send home taxi suddenly come questionthere n crossroad city bidirectional road connect a taxi ride path crossroad pass crossroad twice you collection ride driver wonder driver robot definitely humanyou think driver robot crossroad b driver choose path drive b note b endpoint ride path b different on contrary driver drive different path b definitely humangiven system road description ride available determine driver robot
0array
arkadys morning straight nightmare he overslept morning halfasleep get tram arrive some time leave tram realize sure line number tram inDuring ride Arkady wake time time see tram stop stop for stop know line tram stop give information help Arkady determine possible line tram
2string
alice hair grow leap bound maybe cause excess vitamin maybe black magicto prevent Alice decide hairdresser she want hair length l centimeter haircut l favorite number suppose alice head straight line n hairline grow Lets number 1 n with swing scissor hairdresser shorten hairlines segment length l give hairline segment length strictly great l the hairdresser want complete job fast possible possible number swing scissor swing scissor take secondAlice have not decide hairdresser ask calculate time haircut depend time hairdresser in particular need process query type 0 Alice ask time haircut hairdresser 1 p d pth hairline grow d centimeter note request 0 Alice interested hypothetical scenario take haircut hairline change length
1graph
the king country N decide completely rebuild road network there n people live country enumerate 1 n it possible construct road house citizen house citizen b there road pair citizen the road network connect ie possible reach citizen start road to save fund decide build exactly n1 road road network treeHowever easy sound that s king address help there m secret community country unite nonempty subset citizen the king want conflict community want build network house member society form connect subtree network a set vertex form connect subtree graph remain connect delete vertex edge one connect vertex sethelp king determine possible build desire road network build
1graph
at break Vanya come class see array n kbit integer a_1 a_2 ldots a_n board an integer x call kbit integer 0 leq x leq 2k 1 of course Vanya able resist start change number write board to ensure note Vanya allow type change choose index array 1 leq leq n replace number a_i number overlinea_i we define overlinex kbit integer x kbit integer k bit differ corresponding bit x Vanya like number 0 therefore like segment l r 1 leq l leq r leq n a_l oplus a_l1 oplus ldot oplus a_r neq 0 oplus denote bitwise XOR operation determine maximum number segment like Vanya apply zero operation describe
2string
there n child number 1 n kindergarten Kindergarten teacher give a_i 1 leq a_i leq n candy ith child Children seat row order 1 n leave right start eat candy while ith child eat candy calculate number l_i r_i number child seat leave get candy number child seat right get candy respectivelyformally l_i number indice j 1 leq j a_i a_j r_i number indice j j leq n a_i a_jEach child tell kindergarten teacher number l_i r_i calculate unfortunately forgot candy give child so ask help give array l r determine give candy child child correctly calculate value l_i r_i definitely mistake if possible find way
1graph
suppose give sequence S k pair integer a_1 b_1 a_2 b_2 dots a_k b_kYou perform follow operation choose position increase a_i 1 that perform exist position j ne j a_i a_j the cost operation b_i choose position decrease a_i 1 that perform exist position j a_i a_j 1 the cost operation b_i each operation perform arbitrary number time possibly zerolet fs minimum possible x exist sequence operation total cost x a_i S pairwise distinct now task you give sequence p consist n pair integer a_1 b_1 a_2 b_2 dots a_n b_n all b_i pairwise distinct Let p_i sequence consist pair p your task calculate value fP_1 fp_2 dot fP_n
1graph
you give set integer l r inclusive l r r l 1 le 3 cdot 105 r l oddyou want split number exactly fracr l 12 pair way pair j great common divisor j equal 1 each number appear exactly pairsprint result pair output solution exist if multiple solution print
2string
there n point plane x_1y_1 x_2y_2 ldot x_ny_nYou need place isoscele triangle side coordinate axis cover point point cover lie inside triangle triangle calculate minimum length short triangle
1graph
formula 1 official decide introduce new competition car replace space ship number point award differ racegiven current rank competition point distribution race task calculate well possible ranking give astronaut race its guarantee give astronaut unique number point race
2string
after learn lot space exploration little girl name Ana want change subjectana girl love palindrome string read backwards forward she learn check give string palindrome soon grow tired problem come interesting need help solve ityou give array string consist small letter alphabet your task find palindrome pair array a palindrome pair pair string follow condition hold permutation concatenation string palindrome in word string let aab abcac concatenate aababcac check exist permutation new string palindrome case exist permutation aabccbaa two pair consider different string locate different index the pair string index ij consider pair ji
1graph
in mission MDCS successfully ship N AI robot Mars before start explore system initialization require arranged line every robot describe number position x_i radius sight r_i iq q_isince intelligent robot talk Radius sight inclusive robot robot range x_i r_i x_i r_i but do not walk talk anybody robot similar iq by similar IQ mean absolute difference is not K Help calculate pair robot go talk timely update software avoid potential quarrel
1graph
let t tree n vertex consider graph G_0 initially equal t you give sequence q update ith update give pair distinct integer u_i v_i for 1 q define graph g_i follow if G_i1 contain edge u_i v_i remove edge form g_i otherwise add edge G_i1 form g_i Formally g_i G_i1 triangle u_i v_i triangle denote set symmetric difference furthermore guarantee t subgraph g_i in word update remove edge TConsider connected graph H run depthfirst search one tree edge ie edge lead visit vertex time traversal form span tree graph h this span tree generally fix particular graph depend start vertex order neighbor vertex traverse we vertex w good order neighbor vertex way depthfirst search start w produce t span tree for 1 q find report number good vertex
1graph
you give n point plane the polygon form n point strictly convex polygon convex collinear point ie lie straight line the point number 1 n clockwise orderWe define distance point p_1 x_1 y_1 p_2 x_2 y_2 Manhattan distance dp_1 p_2 x_1 x_2 y_1 y_2Furthermore define perimeter polygon sum Manhattan distance adjacent pair point point polygon order p_1 p_2 ldot p_k k geq 3 perimeter polygon dp_1 p_2 dp_2 p_3 ldot dp_k p_1For parameter k let consider polygon form give set point have k vertex polygon selfintersecte for polygon let consider perimeter over perimeter define fk maximal perimeterplease note check polygon selfintersecte edge polygon draw straight line for instance follow picture in middle polygon order point p_1 p_3 p_2 p_4 valid selfintersecting polygon the right polygon edge resemble Manhattan distance order selfintersecte consider edge straight line the correct way draw polygon p_1 p_2 p_3 p_4 leave polygonYour task compute f3 f4 ldot fn in word find maximum possible perimeter possible number point ie 3 n
2string
on chessboard width 109 height 109 row number 1 109 column number leave right 1 109 therefore cell chessboard assign coordinate xy x column number y row numberevery day fight black white piece board today black one win price only rook survive drive low leave corner cell coordinate 11 but happy victory win time celebrate in order rook need home upper field cell row number 109everything fine treacherous white figure spell place field end game there type spell Vertical each define number x such spell create infinite blocking line column x x1 Horizontal each define number x_1 x_2 y such spell create block segment pass cell row y column x_1 x_2 inclusive the peculiarity spell impossible certain pair spell common point note horizontal spell common point vertical spell an example chessboard Lets recall rook chess piece point row column initial position in task rook cell r_0c_0 cell r_1c_1 condition r_1 r_0 c_1 c_0 block line block segment cell for well understanding look samplesfortunately rook remove spell tremendous effort wants remove minimum possible number spell way return home find number
2string
Bajtek know unusual gift recently get integer array x_0 x_1 ldot x_k1unfortunately huge arrayparty extraordinary friend realize he d lose after hour spend search new toy Bajtek find array producer website array length n 1 as formal description say a_0 0 i1 le le n a_i x_i1bmod k a_i1 p bmod q denote remainder division p qFor example x 1 2 3 n 5 a_0 0 a_1 x_0bmod 3a_0x_001 a_2 x_1bmod 3a_1x_113 a_3 x_2bmod 3a_2x_236 a_4 x_3bmod 3a_3x_067 a_5 x_4bmod 3a_4x_179 so x 1 2 3 n 5 0 1 3 6 7 9now boy hope able restore x Knowing 1 le k le n help find possible value k possible length lose array
1graph
recently Monocarp get job his work day last exactly m minute during work Monocarp want drink coffee certain moment n minute a_1 a_2 dot a_n able willing coffee break sake simplicity let consider coffee break last exactly minute however Monocarps boss do not like Monocarp take coffee break so give coffee break go minute a_i Monocarp choose day drink coffee say minute day d minute pass coffee break Monocarp want n coffee break minimum possible number work day do not count day work do not coffee break day take account d minute pass end work day start follow work dayfor n give minute determine day Monocarp coffee break minute you minimize number day spend
1graph
while people enjoy spend time solve programming contest Dina prefer take beautiful picture as soon Byteland Botanical Garden announce Summer Oenothera Exhibition decide test new camera therethe exhibition consist l 10100 Oenothera specie arrange row consecutively number integer 0 l 1 camera lens allow photo w specie ie Dina photo contain flower index x x w 1 integer x 0 l w we denote photo x x w 1she take n photo ith chronological order x_i x_i w 1 notation she decide build timelapse video photo discover oenothera blossom open evening Dina take photo truncate leave segment contain exactly k flower compose video photo keep original order voilà beautiful artwork createdA scene contiguous sequence photo set flower the change scene call cut for example consider photo contain flower 1 5 second photo contain flower 3 7 photo contain flower 8 12 if k 3 Dina truncate second photo 3 5 photo 9 11 first photo form scene photo form scene transition scene happen second photo cut if k 4 transition photo cutDina want number cut small possible please help calculate minimum possible number cut different value k
1graph
a tree undirected graph exactly simple path pair vertex we set simple path kvalid vertex tree belong path include endpoint path consist exactly k verticesyou give tree n vertex for k 1 n inclusive find maximum possible size kvalid set simple path
1graph
the BFS algorithm define follow consider undirected graph vertex number 1 n initialize q new queue contain vertex 1 mark vertex 1 Extract vertex v head queue q Print index vertex v Iterate arbitrary order vertice u u neighbor v marked Mark vertex u insert tail queue q if queue continue step 2 otherwise finish since order choose neighbor vertex vary turn multiple sequence BFS printIn problem need check give sequence correspond valid bfs traversal give tree start vertex 1 the tree undirected graph exactly simple path vertex
1graph
little D friend Little C love interval instead number 3now n interval number axi ith a_ib_ionly n interval satisfy he define value interval interval lr 1 leq l leq r leq n l r integer total length union interval lth rthHe want select exactly k different interval interval sum value maximal please help calculate maximal sum
0array
you give n integer a_1 a_2 ldot a_n each a_i 3 5 divisor consider prod a_i product input integer find number divisor as number large print modulo prime number 998244353
2string
you set n weight you know masse a_1 a_2 a_n gram do not know mass you can not distinguish weightsHowever friend know mass weight you ask friend exactly k weight total mass m parameter k m choose friend point valid subset weight possibleyou allow query find maximum possible number weight reveal query
1graph
at competition word cup official winner present actual cup this time organizer unusual programming competition decide winner add nameplate cup handle winnerthe nameplate rectangular text print table row column have measurement organizer find number row great 5 number b column exceed 20 every cell table contain asterisk letter user handlefurthermore organizer want row table uniform mean number asterisk different row differ ie can not asterisk row second the main goal obtain winner handle precisely read table leave right row skip asterisksthe organizer want nameplate row possible valid table minimum number row want choose minimum number columnsthe winner determine task write program give certain handle generate necessary table
1graph
you give array length n consist zero onesyou perform follow operation multiple time the operation consist step choose integer 1 le x y z le n form arithmetic progression y x z y Flip value a_x a_y a_z ie change 1 0 change 0 1 determine possible element array equal zero if yes print operation lead allzero state your solution contain lfloor fracn3 rfloor 12 operation here lfloor q rfloor denote number q round we possible element equal zero number operation possible
2string
you give matrix size n time n fill lowercase english letter you change k letter matrixConsider path upper left corner low right corner cell neighboring cell right each path associate string form letter cell path visit thus length string 2n 1find lexicographically small string associate path change letter k cell matrixa stre lexicographically small string b different letter b small
1graph
you give tuple generator fk f_1k f_2k dot f_nk f_ik a_i cdot f_ik 1 b_i bmod p_i f0 x_1 x_2 dot x_n here x bmod y denote remainder x divide you all p_i primesOne fix sequence x_i y_i a_i tuple fk start index repeat tuple small index calculate maximum number different tuple fk k ge 0 produce generator x_i a_i b_i integer range 0 p_i 1 choose arbitrary the answer large print remainder gives divide 109 7
1graph
Vasya own cornfield define integer n d the cornfield represent rectangle vertex have cartesian coordinate 0 d d 0 n n d n d n an example cornfield n 7 d 2 Vasya know m grasshopper near field maybe inside the ith grasshopper point x_i y_i Vasya like grasshopper eat corn grasshopper want know position inside cornfield include border outsidehelp Vasya for grasshopper determine inside field include border
2string
there infinite board square tile initially tile whitevova red marker blue marker red marker color tile blue marker color b tile if tile is not white can not use marker color each marker drain completely end exactly red tile exactly b blue tile boardvova want color set tile form rectangle consist exactly ab colored tile tile color form rectangle here example correct coloring here example incorrect coloring among correct coloring Vova wants choose minimal perimeter what minimal perimeter Vova obtainit guarantee exist correct coloring
1graph
you give problemset consist n problem the difficulty ith problem a_i it guarantee difficulty distinct give increase orderyou assemble contest consist problem give problemset in word contest assemble subset problem necessary consecutive give problemset there condition satisfied problem hard problem maximum difficulty problem difficulty great difficulty problem great twice difficulty problem in word let a_i_1 a_i_2 dot a_i_p difficulty select problem increase order then j 1 p1 a_i_j 1 le a_i_j cdot 2 hold it mean contest consist problem validAmong contest satisfy condition assemble maximum number problem your task find number problem
2string
we array b_1 b_2 ldot b_m good exist index j b_i cdot b_j perfect squaregiven array b_1 b_2 ldot b_m action perform follow multiply element b_i prime p divide element b_i prime p b_i divisible p let fb_1 b_2 ldot b_m minimum number action need array b goodYou give array n integer a_1 a_2 ldot a_n q query form l_i r_i for query output fa_l_i a_l_i 1 ldot a_r_i
1graph
consider set point a initially there type query Insert point x_i y_i a it guarantee point belong a moment Remove point x_i y_i a it guarantee point belong a moment give point x_i y_i calculate minimum number point require add a a symmetrical respect line contain point 0 0 x_i y_i note point actually add a ie query independent
1graph
polycarp study Berland State University soon exam he pass exactly n examsfor exam know day a_i day opportunity pass exam b_i day second opportunity pass exam a_i b_i Polycarp pass exam day for exam Polycarp choose day pass exam he pass n examspolycarp wants pass exam soon possible Print minimum index day Polycarp pass n exam print 1 pass exam
1graph
you n stick give lengthsyour task choose exactly way form rectangle no stick cut piece rectangle form single stick no stick choose multiple time it guarantee possible choose stickslet s area rectangle p perimeter rectangle the choose rectangle value fracp2s minimal possible the value take roundingif multiple answer print themeach testcase contain list stick require solve problem separately
2string
you give string s consist n lowercase latin letter n evenfor position 1 le le n stre s require change letter position previous letter alphabetic order letter z option Letter position change exactly oncefor example letter p change o q letter change b letter z change yThat way string codeforce example change dpedepqbft c rightarrow d o rightarrow p d rightarrow e e rightarrow d f rightarrow e o rightarrow p r rightarrow q c rightarrow b e rightarrow f s rightarrow tString s call palindrome read leave right right leave for example string abba zz palindrome string abca zy notyour goal check possible string s palindrome apply aforementione change position Print yes string s transform palindrome no otherwiseEach testcase contain string require solve problem separately
2string
during research property great common divisor GCD set number Ildar famous mathematician introduce brand new concept weaken common divisor WCD list pair integersfor give list pair integer a_1 b_1 a_2 b_2 a_n b_n WCD arbitrary integer great 1 divide element pair WCD exist listsfor example list look like 12 15 25 18 10 24 wcd equal 2 3 5 6 number strictly great 1 divide number pairyoure currently pursue phd degree Ildars mentorship that s problem delegate your task calculate WCD efficiently
1graph
by year 3018 Summer Informatics School greatly grow Hotel Berendeetronik choose location school the camp consist n house n1 pathway it possible reach house pathwayseverythe perfect rain start the weather forecast promise rain continue m day a special squad teacher able measure ith pathway connect house u_i v_i rain pass b_i second unfortunately rain erode road day time pass road increase a_i second in word tth zero day start rain a_i cdot t b_i second pass roadunfortunately despite effort teacher year 3018 student house midnight as midnight student bed important find maximal time pair house day student know time run houseFind maximal time path pair house t0 t1 tm1 day
1graph
in the Man High Castle world m different film ending Abendsen own storage shelf at n order film shelf in ith month empty storage Put k_i cdot m film storage k_i film end he think question put film shelf storage randomly pick n film film storage rearrange shelf probability sequence ending l_i r_i shelf change Notice think question shelf actually changedanswer abendsen questionslet probability fraction p_i Lets total number way n film storage ith month A_i P_i cdot A_i integer Print month P_i cdot A_i pmod 998244353998244353 prime number equal 119 cdot 223 1it guarantee 100 different k value
1graph
Abendsen assign mission Juliana in mission Juliana root tree n vertex vertex number 1 root tree each vertex black white at vertex white Juliana ask process q query each query type if vertex v white mark black perform operation direct son v instead Mark vertice subtree v include v white Find color ith vertex an example operation 1 1 correspond example test the vertex 1 2 black operation go son instead can help Juliana process query
1graph
you give bracket sequence s necessarily regular a bracket sequence string contain character a regular bracket sequence bracket sequence transform correct arithmetic expression insert character 1 original character sequence for example bracket sequence regular result expression 11 111 notyour problem calculate number regular bracket sequence length 2n contain give bracket sequence s substre consecutive sequence character modulo 1097 1000000007
1graph
welcome innopolis city throughout year innopolis citizen suffer everlaste city construction from window room sequence n hills ith height ai the Innopolis administration want build house hill however sake city appearance house build hill strictly high neighbouring hill present for example sequence height 5462 house build hill height 5 6 onlyThe innopolis administration excavator decrease height arbitrary hill hour the excavator work hill time it allow decrease hill zero height negative value increase height hill impossible the city administration wants build k house k hills satisfy condition what minimum time require adjust hill achieve administration planhowever exact value k determined calculate answer k range here denote n divide rounded
0array
Natasha travel Mars Mars rover but suddenly break logical scheme inside the scheme undirected tree connect acyclic graph root vertex 1 leaf exclude root input vertex logical element include root output one bit fed input one bit return outputthere type logical element and 2 input or 2 input XOR 2 input not 1 input logical element value direct descendant input return result function perform Natasha know logical scheme Mars rover fact input break in order fix Mars rover need change value inputfor input determine output Natasha change input
2string
leha planning journey Moscow Saratov he hate train decide city carthe path Moscow Saratov represent straight line straight reality problem consider straight distance Moscow Saratov n km Lets Moscow situate point coordinate 0 km Saratov coordinate n kmdrive long time difficult Formally Leha cover kilometer stop rest consider difficulty cover 1th kilometer a_i 1 it guarantee 1 n 1 a_i le a_i 1 the difficulty journey denote sum difficulty kilometer journeyfortunately rest site Moscow Saratov every integer point 1 n 1 contain rest site when Leha enter rest site rest kilometer difficulty a_1 kilometer difficulty a_2 onFor example n 5 rest site coordinate 2 difficulty journey 2a_1 2a_2 a_3 kilometer difficulty a_1 second a_2 Leha rest kilometer difficulty a_1 fourth a_2 a_3 another example n 7 rest site coordinate 1 5 difficulty Lehas journey 3a_1 2a_2 a_3 a_4Leha do not know integer point contain rest site so consider possible situation obviously 2n 1 different distribution rest site distribution different exist point x contain rest site exactly distribution Leha consider distribution equiprobable he want calculate p expect value difficulty journeyobviously p cdot 2n 1 integer number you calculate modulo 998244353
1graph
you give ternary string string consist character 0 1 2you swap adjacent consecutive character 0 1 ie replace 01 10 vice versa adjacent consecutive character 1 2 ie replace 12 21 vice versaFor example string 010210 perform follow move 010210 rightarrow 100210 010210 rightarrow 001210 010210 rightarrow 010120 010210 rightarrow 010201 note swap 02 rightarrow 20 vice versa you perform operation give string exclude describe aboveyou task obtain minimum possible lexicographically string swap arbitrary number time possibly zerostre lexicographically stre b string b length exist position 1 le le s length string s j hold a_j b_j a_i b_i
1graph
Vitya start learn berlanese language it know Berlanese use latin alphabet Vowel letter o u e other letter consonantin Berlanese vowel consonant letter vowel the exception consonant n letter letter vowel letter for example word harakiri yupie man nbo Berlanese word horse king nz notHelp Vitya find word s berlanese
2string
in simplified version Mini Metro game subway line train direction there n station line a_i people wait train ith station begin game the game start begin 0th hour at end hour couple minute end hour b_i people instantly arrive ith station if moment number people ith station large c_i losea player train appoint hour the capacity train k passenger in middle appoint hour train go 1st nth station take people station accommodate a train people ith station people i1th stationif multiple train appoint hour capacity add move togetherThe player want stay game t hour determine minimum number train need
1graph
you give array integer Vasya permute change order integer he want possible integer place small integer stand help Vasya find maximal number integersfor instance give array 10 20 30 40 permute 20 40 10 30 then second position integer large 2010 4020 fourth permutation number Vasya want maximize equal 2 read note example demonstrative test caseHelp Vasya permute integer way number position new array integer great original maximal
1graph
polycarp practice problem solve skill he list n problem difficulty a_1 a_2 dot a_n respectively his plan practice exactly k day each day solve problem list Polycarp solve problem order give list skip problem list he solve n problem exactly k daysThus day Polycarp solve contiguous sequence consecutive problem start list he can not skip problem solve multiple time as result k day solve n problemsThe profit jth day Polycarps practice maximum difficulty problem Polycarp solve jth day ie solve problem indice l r day profit day maxlimits_l le le ra_i the total profit practice sum profit k day practiceyou want help Polycarp maximum possible total profit valid way solve problem your task distribute n problem k day satisfy condition way total profit maximumfor example n 8 k 3 5 4 2 6 5 1 9 2 possible distribution maximum total profit 5 4 2 6 5 1 9 2 here total profit equal 5 6 9 20
2string
there n city Berland some pair city connect road all road bidirectional each road connect different city there road pair city the city number 1 nit know capital city number 1 reach city move roadsThe President Berland plan improve countrys road network the budget repair exactly n1 road the President plan choose set n1 road possible travel capital city n1 choose road d_i number road need travel capital city move n1 choose road d_1 d_2 dot d_n minimize ie minimal possible in word set n1 road preserve connectivity country sum distance city 1 city minimize use n1 choose roadsthe president instruct ministry prepare k possible option choose n1 road condition metWrite program find k possible way choose road repair if few k way program output possible valid way choose road
1graph
a sequence a_1 a_2 dot a_n call good element a_i exist element a_j ne j a_ia_j power 2d nonnegative integer dFor example follow sequence good 5 3 11 example a_15 choose a_23 note sum power similarly element find a_2 a_3 1 1 1 1023 7 39 89 25 89 note definition sequence length 0 goodFor example follow sequence good 16 a_116 impossible find element a_j sum power 4 16 a_14 impossible find element a_j sum power 1 3 2 8 8 8 a_32 impossible find element a_j sum power you give sequence a_1 a_2 dot a_n what minimum number element need remove good you delete arbitrary set element
2string
little girl Tanya climb stair inside multistorey building every time Tanya climb stairway start count step 1 number step stairway she speak number aloud for example climb stairway contain 3 step second contain 4 step pronounce number 1 2 3 1 2 3 4you give number pronounce Tanya how stairway climb also output number step stairwayThe give sequence valid sequence Tanya pronounce climbing stairway
1graph
Sonya like ice cream she eat programming competition that girl decide want open ice cream shopsSonya live city n junction n1 street all street twoway connect junction it possible travel junction street City Hall allow opening shop junction the girl open shop middle street Sonya exactly k friend trust if open shop friend work allow anybody eat ice cream pay since Sonya want skip important competition work shop personallySonya want ice cream shop form simple path length r 1 le r le k ie locate different junction f_1 f_2 dot f_r street f_i f_i1 1 r1the girl take care potential buyer wants minimize maximum distance junction near ice cream shop the distance junction b equal sum street length need pass junction junction b so Sonya want minimizemax_a min_1 le le r d_af_iwhere take value possible n junction f_i junction ith Sonyas shop locate d_xy distance junction x ySonya sure find optimal shop location ask help open k shop form simple path maximum distance junction near shop minimal
1graph
polycarp n coin value ith coin a_i it guarantee value integer power 2 ie a_i 2d nonnegative integer number dPolycarp wants know answer q query the jth query describe integer number b_j the answer query minimum number coin necessary obtain value b_j subset coin Polycarp use coin if Polycarp can not obtain value b_j answer jth query 1the query independent answer query do not affect Polycarps coin
1graph
polycarp n coin value ith coin a_i Polycarp want distribute coin pocket coin value pocketFor example Polycarp get coin represent array 1 2 4 3 3 2 distribute coin pocket follow 1 2 3 2 3 4polycarp wants distribute coin minimum number pocket help
2string
you give quantum oracle operation n1 qubit implement function you guarantee function f implement oracle scalar product function oracle problem d1 here array n integer 0 1 your task reconstruct array your code allow give oracle onceyou implement operation take follow input integer N number qubit oracle input 1n8 oracle Uf implement operation signature Qubit Qubit ie operation take input array qubit output qubit outputthe return operation array integer length n 0 1your code follow signaturenamespace solution open MicrosoftQuantumPrimitive open MicrosoftQuantumCanon operation Solve N Int Uf Qubit Qubit Int body code
2string
you give 2 qubit guarantee orthogonal state your task perform necessary operation measurement figure state return index state 0 1 etc the state qubit operation matteryou implement operation take array 2 qubit input return integer your code follow signaturenamespace solution open MicrosoftQuantumPrimitive open MicrosoftQuantumCanon operation Solve qs Qubit Int body code
1graph
you give n qubit guarantee basis state n qubit you give bitstring bits0 bits1 describe basis statesyour task perform necessary operation measurement figure state return 0 state describe bits0 1 state describe bits1 the state qubit operation matter
1graph
you give qubit state integer sign your task convert give qubit state sign1 sign1
1graph
you give weight tree undirecte connect graph cycle loop multiple edge n vertex the edge u_j v_j weight w_j also vertex value a_i assign itlet path start vertex u end vertex v edge appear twice regardless direction 2path vertex appear 2path multiple time start end verticesFor 2path p profit textprp sumlimits_v textdistinct vertex pa_v sumlimits_e textdistinct edges pk_e cdot w_e k_e number time edge e appear p that vertex count edge count number time appear pyou answer m query each query pair vertex qu qv for query find 2path p qu qv maximal profit textprp
1graph
there lot way fun inflatable balloon for example fill water happensGrigory Andrew opinion so time go shop buy n packet inflatable balloon ith exactly a_i balloon insidethey want divide balloon in addition condition hold do rip packet Grigory Andrew unbroken packet Distribute packet packet give Give Grigory Andrew packet to provide fun total number balloon grigorys packet equal total number balloon Andrews packet help divide balloon determine impossible condition
1graph
Allen host formal dinner party 2n people come event n pair couple after night fun Allen want line final picture the 2n people line Allen do not like order Allen prefer pair occupy adjacent position line make picture aesthetichelp Allen find minimum number swap adjacent position perform couple occupy adjacent position line
0array
there small spaceship surround group enemy large spaceship the space twodimensional plane group enemy spaceship position way integer ycoordinate xcoordinate equal 100 second group position way integer ycoordinate xcoordinate equal 100each spaceship group simultaneously shoot laser shot infinite ray destroy spaceship touch small spaceship time the small spaceship able avoid laser shot want position location x0 necessarily integer ycoordinate ray shot destroy enemy spaceship possible find large number spaceship destroy way assume enemy spaceship can not avoid laser shot
2string
today Informatics class Nastya learn GCD LCM link Nastya intelligent solve task momentarily suggest solve wellWe define pair integer ab good GCDabx LCMaby GCDab denote great common divisor b LCMab denote common multiple bYou give integer x y you find number good pair integers ab labr Note pair ab ba consider different ab
1graph
this night was not easy Vasya his favorite team lose do not find victorious play perfectly teammate let time he win time losestreak grow long long its wonder do not sleep night allIn morning Vasya wait bus university bus stop Vasyas thought hazy could not remember right bus number right get bus number nin bus Vasya think order digits number bus wrong Futhermore digit time digit see definitely real number bus for example Vasya see number 2028 mean real bus number 2028 8022 2820 820 however number 80 22208 52 definitely could not number bus also real bus number could not start digit 0 mean example number 082 could not real bus number tooGiven n determine total number possible bus number variant
1graph
translator note Russias widespread grade system grade 5 4 3 2 high well roughly correspond a b c F respectively american grade systemthe term come end student start think grade Today professor tell student grade course given automatically calculate simple average arithmetic mean grade give lab work term round near integer the round favour student 45 round 5 example 3 44 round 4this bode Vasya do not think lab work influence receive grade bad 5 maybe dread 2 however professor allow redo work Vasyas choose increase average grade Vasya want redo lab work possible order 5 course of course Vasya 5 lab work choose redohelp Vasya calculate minimum lab work Vasya redo
2string
each student eagerly await day pass exam successfully thus Vasya ready celebrate ala do not pass however Vasyas fellow student group successful celebrate examSome celebrate BugDonalds restaurant BeaverKing restaurant successful one fast celebrate restaurant student do not pass exam do not celebrate restaurant elect stay home prepare reexamination however quickly bore Vasya start check celebration photo Kilogramm he find total BugDonalds visit a student BeaverKing b student c student visit restaurant Vasya know N student groupbase info Vasya want determine data contradict do not student group do not pass exam can help will not waste valuable preparation time
1graph
give number n b you need find adjacency matrix undirected graph number component equal number component complement b the matrix symmetric digit main diagonal zeroesin undirected graph loop edge vertex allow it edge pair verticesthe adjacency matrix undirected graph square matrix size n consist 0 1 n number vertex graph ith row ith column correspond ith vertex graph the cell ij adjacency matrix contain 1 ith jth vertices graph connect edgeA connect component set vertex x vertex set exist path graph connect pair vertex add vertex x violate ruleThe complement inverse graph g graph H vertice distinct vertex h adjacent adjacent g
1graph
gather darkness shroud wood world the moon shed light boat riverto curtain moonlight hardly possible shade present mellow beauty restful nature Intonates MinoSee the cloud come Kanno gaze distancethat can not well Mino turn Kanno the sky see onedimensional axis the moon origin coordinate 0There n cloud float sky each cloud length l the ith initially cover range x_i x_i l endpoint exclude Initially move velocity v_i equal 1 1furthermore pair cloud intersect initially 1 leq lt j leq n lvert x_i x_j rvert geq lwith wind velocity w velocity ith cloud v_i w that coordinate increase v_i w unit time Note wind strong cloud change directionyou help Mino count number pair j j proper choice wind velocity w exceed w_mathrmmax absolute value possibly negative andor fractional ith jth clouds cover moon future moment this w do not need different pair
2string
walk riverside Mino silently take note somethingTime Mino think aloudwhattime tide wait man explain Mino my take river remind thisAnd recordingyou tide everything period I think I ve figure say Mino confidencedoubtfully Kanno peek Minos record the record express string s character 0 1 0 denote low tide 1 denote high tide denote unknown high lowyou help Mino determine possible replace independently 0 1 give integer p period result string in case answer yes replacement MinoIn problem positive integer p consider period string s 1 leq leq lvert s rvert p ith pth character s here lvert s rvert length s
1graph
there n distinct point coordinate line coordinate ith point equal x_i choose subset give set point distance pair point subset integral power it necessary consider pair point adjacent Note subset contain element satisfie condition among subset choose subset maximum possible sizein word choose maximum possible number point x_i_1 x_i_2 dot x_i_m pair x_i_j x_i_k true x_i_j x_i_k 2d d nonnegative integer number necessarily pair point
2string
you give n string each string consist lowercase english letter Rearrange reorder give string way string string place substringsstre substre string b possible choose consecutive letter b way form for example string contain substre string codeforce contain substre string fofo rof
1graph
it middle 2018 Maria Stepanovna live outside Krasnokamensk town Zabaikalsky region want rent display highlight important problemthere n display place road ith display text font size s_i Maria Stepanovna want rent display indice j k font size increase road particular direction namely condition s_i s_j s_k heldThe rent cost ith display c_i please determine small cost Maria Stepanovna pay
1graph
Petr like come problem randomly generate datum this time problem random permutation he decide generate random permutation way take identity permutation number 1 n 3n time take random pair different element swap Alex envy Petr try imitate kind thing Alex come problem random permutation he generate random permutation like Petr swap element 7n1 time instead 3n time because random okyou test problem want know
1graph
you give stre s length n consist lowercase English lettersfor give string s t S set distinct character s t set distinct character t the string s t isomorphic length equal onetoone mapping bijection f S T fsiti Formally fsiti index character exactly character fxy character exactly character fxy for example string aababc bbcbcz isomorphic Also string aaaww wwwaa isomorphic the follow pair string isomorphic aab bbb test bestyou handle m query characterized integer xylen 1xynlen1 for query check substring sx xlen1 sy ylen1 isomorphic
2string
you go beach idea build great sand castle head the beach threedimensional imagine decribed line spot pile sand pillar spot number 1 infinity leave right obviously sand beach bring n pack sand let height hi sand pillar spot number sand pack spend you can not split sand pack multiple pillar sand single there fence height equal height pillar h sand pack leave spot prevent sand going finally end follow condition build castle h1H sand leftmost spot fence for hihi11 large difference height neighboring pillar lead sand fall higher low do not want happen want spend sand bring as infinite spot build possible come valid castle structure though want castle compact possible your task calculate minimum number spot occupy aforementioned condition hold
2string
in NN country n city number 1 n n 1 road connect there road path citiesThere m bidirectional bus route city Buses drive city take short path stop city drive travel bus travel stop route you travel city busyou interested q question possible city minimum number bus need use
1graph
you give tree n vertex you select k necessarily distinct simple path way possible split edge tree set edge contain path edge exactly path edge part select path set nonemptycompute number way select k path modulo 998244353the path enumerate word way consider distinct 1 leq leq k edge ith path contain edge way contain
1graph
Ramesses know lot problem involve tree undirecte connect graph cycleshe create new useful tree decomposition know construct ask helpThe decomposition split edge tree simple path way path common vertex each edge tree exactly pathhelp remesse find decomposition tree derermine decomposition
1graph
two famous compete company ChemForces TopChemist decide set recently discover chemical element exhibition however know element present set companiesIn order avoid representative company decide agreement set company present the set choose way maximize total income companiesall element enumerate integer the ChemForces company discover n distinct chemical element index a_1 a_2 ldots a_n income x_i Berland ruble ith element list set companyThe TopChemist company discover m distinct chemical element indice b_1 b_2 ldots b_m income y_j Berland ruble include jth element list setin word company present subset element a_1 a_2 ldot a_n possibly subset second company present subset element b_1 b_2 ldot b_m possibly subset there should not equal element subsetshelp representative select set way element present set total income maximum possible
1graph
in BerSoft n programmer work programmer characterize skill r_iA programmer mentor programmer b skill programmer strictly great skill programmer b r_a r_b programmer b quarrelyou give skill programmer list k pair programmer quarrel pair unordere for programmer find number programmer programmer mentor
1graph
you give bipartite graph GUVE U set vertex V set vertex second e set edge there multiple edgeslet subset edge kcovere iff graph vertex incident k edge Minimal kcovering kcovering size subset minimal possibleyour task find minimal kcovere mindegree minimal degree vertex graph g
0array
ghost live harmony peace travel space purpose scare stand waythere n ghost universe OXY plane velocity change time overrightarrowV v_xoverrightarrowi v_yoverrightarrowj v_x speed xaxis V_y yaxisA ghost experience value EX_i represent ghost try scare past two ghost scare cartesian point moment timeAs ghost constant speed moment time scare relief experience ghost kind gx sum_i1n EX_i increasetameem red giant take picture cartesian plane certain moment time T magically ghost aligned line form y cdot x b you compute experience index ghost kind gx indefinite future task todayNote Tameem take picture gx great 0 ghost scared moment infty t
2string
arkadys code contain n variable each variable unique consist lowercase English letter one day Arkady decide shorten codeHe want replace variable nonempty prefix new name unique new variable coincide old variable among possibility wants find way small possible total length new namesA string prefix string b delete possibly character end b obtain aPlease find minimum possible total length new name
1graph
Arkady play Battleship the rule game are not importantthere field n time n cell there exactly kdeck field ie ship k cell long orient horizontally vertically however Arkady do not know locate for cell Arkady know definitely contain shipconsider possible location ship find cell belong maximum possible number different location ship
1graph