question
stringlengths
58
4.29k
label
class label
3 classes
you give string s consist n letter letter b the letter string number 1 nsl r continuous substre letter index l r string inclusive a string call balanced number letter equal number letter b for example string baba aabbab balanced strings aaab b notFind nonempty balanced substring sl r string s Print l r 1 le l le r le n if substre print 1 1
1graph
Alice grid n row m column some cell mark mark cell adjacent edge grid two square adjacent share Alice want fill cell number follow statement true unmarked cell contain number 1 4 mark cell contain sum number unmarke cell adjacent mark cell adjacent unmarke cell sum 0 marked cell contain multiple 5 Alice could not figure ask Bob help help Bob find grid state grid exist
1graph
you give positive integer n s find maximum possible median array n nonnegative integer necessarily distinct sum element equal sa median array integer length m number stand lceil fracm2 rceilth round position nondecrease order element position number start 1 for example median array 204020505030 lceil fracm2 rceilth element 202030405050 30 there exist definition median problem use describe definition
1graph
it simplify version problem f2 the difference constraint F1 k le 2 F2 k le 10You give integer n find minimum integer x x ge n number x kbeautifulA number call kbeautiful decimal representation having lead zero contain k different digit Eg k 2 number 3434443 55550 777 21 kbeautiful number 120 445435 998244353
0array
this hard version problem the difference version constraint n you hack version problem solvedA forest undirected graph cycle necessarily connectedMocha Diana friend Zhijiang forest node number 1 n like add edge forest after add edge graph forest they add edge that edge u v add Mochas forest edge u v add Dianas forest vice versa Mocha Diana want know maximum number edge add edge add
2string
in certain video game player control hero characterize single integer value powerOn current level hero get system n cave number 1 n m tunnel each tunnel connect distinct cave any cave connect tunnel any cave reach cave move tunnelsthe hero start level cave 1 cave contain monsterthe hero cave tunnel if hero leave cave enter tunnel finish movement arrive opposite end tunnelthe hero use tunnel direction however hero use tunnel twice row Formally hero move cave cave j tunnel head cave immediately head cave connect cave j tunnelIt know tunnel come cave hero find dead end consider requirementTo pass level hero beat monster cave when hero enter cave time fight monster the hero beat monster cave heros power strictly great a_i in case beat monster hero power increase b_i if hero can not beat monster he s fight game end player losesafter hero beat monster cave subsequent visit cave will not consequence cave will not monsters heros power will not change eitherFind small possible power hero start level able beat monster pass level
1graph
note memory limit problem low othersyou vertical strip n cell number consecutively 1 n bottomyou token initially place cell n you token arrive cell 1let token cell x 1 moment one shift token follow kind Subtraction choose integer y 1 x1 inclusive token cell x cell x y Floored division choose integer z 2 x inclusive token cell x cell lfloor fracxz rfloor x divide z rounded Find number way token cell n cell 1 shift print modulo m note way token cell shift way consider distinct check example explanation well understanding
1graph
moamen drawing grid n row 109 column contain digit 0 1 Ezzat notice Moamen draw interested minimum number row need remove grid beautifulA grid beautiful consecutive row column contain 1 rowsezzat number row n m segment grid contain digit 1 every segment represent integer l r represent row number l r represent column segment rowfor example n 3 m 6 segment 111 178 277 21515 311 31515 grid your task tell Ezzat minimum number row remove grid beautiful
2string
Moamen Ezzat playing game they create array n nonnegative integer element 2kmoamen win a_1 a_2 a_3 ldot a_n ge a_1 oplus a_2 oplus a_3 oplus ldot oplus a_nHere denote bitwise and operation oplus denote bitwise XOR operationplease calculate number win Moamen array aas result large print value modulo 1000000007 109 7
1graph
as mention previously William like play video game in favorite game player character universe planet designate binary number 0 2n 1 on planet gate allow player planet planet j binary representation j differ exactly bitwilliam want test handle processing follow query game universe Destroy planet number l r inclusively these planet move anymore figure possible reach planet b planet number planetary gate it guarantee planet b destroy
1graph
William array n integer a_1 a_2 dot a_n in swap neighboring item two item a_i a_j consider neighboring condition j 1 satisfiedWilliam want calculate minimal number swap need perform array contain neighboring item parity
2string
you undirected graph consist n vertex weight edgesA simple cycle cycle graph repeat vertex let weight cycle XOR weight edge consist oflet graph good simple cycle weight 1 a graph bad goodinitially graph then q query follow each query type u v x add edge vertex u v weight x do not graph bad for query print edge add
1graph
you axisaligne rectangle room width W height h low leave corner point 0 0 upper right corner W HThere rectangular table standing room the side table parallel wall lower left corner x_1 y_1 upper right corner x_2 y_2You want place rectangular table room width w height h width table parallel width roomthe problem space place second table intersect problem table touch thoughyou can not rotate table table inside room example table what minimum distance table free space second
2string
you give tree n node as reminder tree connect undirected graph cyclesLet a_1 a_2 ldot a_n sequence integer perform follow operation exactly n time Select unerase node u Assign a_u number unerase node adjacent u then erase node u edge endpoint for integer k 1 n find number modulo 998244353 different sequence a_1 a_2 ldots a_n satisfy follow condition possible obtain perform aforementioned operation exactly n time order operatornamegcda_1 a_2 ldot a_n k here operatornamegcd mean great common divisor element
1graph
you give integer n m find operatornamemex sequence n oplus 0 n oplus 1 ldot n oplus m here oplus bitwise XOR operatoroperatornamemex sequence nonnegative integer smallest nonnegative integer do not appear sequence for example operatornamemex0 1 2 4 3 operatornamemex1 2021 0
1graph
an identity permutation length n array 1 2 3 dot nwe perform follow operation identity permutation length n firstly cyclically shift right k position k unknown thing know 0 le k le n 1 when array cyclically shift right k position result array form take k element original array change relative order append n k element right change relative order n k element for example cyclically shift identity permutation length 6 2 position array 5 6 1 2 3 4 secondly perform follow operation m time pick element array swap you give value n m result array your task find possible value k cyclic shift operation
1graph
you stre s chip place character string after place chip right maybe zero time ie perform follow operation times current position chip position 1 of course move chip right impossible positionafter move chip right leave maybe zero time ie perform follow operation times current position chip position 1 of course move chip leave impossible positionWhen place chip write character chip end action for example s abcdef place chip 3rd character right 2 time leave 3 time write string cdedcbyou give string s t your task determine possible perform describe operation s write string t result
2string
you organizer famous Zurich Music Festival there n singer perform festival identify integer 1 2 dot n you choose order go perform stage you m friend set favourite singer more precisely 1le ile m ith friend like singer s_i1 s_i 2 dot s_i q_iA friend happy singer like perform consecutively arbitrary order an ordering singer valid make friend happyCompute number valid ordering modulo 998244353
2string
on circle lie 2n distinct point follow property choose 3 chord connect 3 disjoint pair point point strictly inside circle belong 3 chord the point number 1 2 dot 2n clockwise orderinitially k chord connect k pair point way 2k endpoint chord distinctyou want draw n k additional chord connect remain 2n k point point endpoint exactly chordin end let x total number intersection n chord Compute maximum value x attain choose n k chord optimallyNote exact position 2n point relevant long property state paragraph hold
1graph
there infinite pond represent number line there n rock pond number 1 n the ith rock locate integer coordinate a_i the coordinate rock pairwise distinct the rock number increase order coordinate a_1 a_2 dots a_na robot frog sit rock number s the frog programmable it base jumping distance parameter d there set jumping distance range if jump distance range set integer k frog jump rock rock distance d k d k inclusive direction the distance rock absolute difference coordinatesyou assign task implement feature frog give integer k determine frog reach rock number rock number s perform sequence jump jump distance range set k the sequence arbitrarily long emptyyou give q testcase feature jth testcase consist integer k Print yes ith rock reachable no otherwiseyou output yes no case example string yes yes yes yes recognize positive answer
1graph
let array consist n positive great 0 integer beautiful follow condition hold 1 n a_i 1 number a_i 1 a_i 2 exist array wellfor example array 5 3 1 beautiful a_1 number a_1 2 3 exist array a_2 number a_2 2 1 exist array a_3 condition a_3 1 hold array 1 2 2 2 2 beautiful a_1 condition a_1 1 hold number a_i number a_i 1 1 exist array array 1 4 beautiful a_2 a_2 2 2 a_2 1 3 exist array a_2 ne 1 array 2 beautiful a_1 a_1 1 1 a_1 2 0 exist array a_1 ne 1 array 2 1 3 beautiful a_1 number a_1 1 1 exist array a_2 condition a_2 1 hold a_3 number a_3 2 1 exist array you give positive integer s find minimum possible size beautiful array sum element equal s
1graph
there chessboard size n n the square ith row jth column leave label ijcurrently Gregor pawn nth row there enemy pawn 1st row on turn Gregor move pawn a pawn square ij i1j pawn destination square additionally pawn square diagonally ij i1j1 i1j1 enemy pawn square the enemy pawn removedgregor want know maximum number pawn reach row 1note Gregor take turn game enemy pawn also Gregors pawn reach row 1 stuck move
1graph
there cell infinite 2dimensional grid label A B F Find length short path A b adjacent cell share visit cell F forbidden obstacle
1graph
this easy version problem the difference k2 you hack version problem solvedthis interactive problemevery decimal number base k equivalent the individual digit base k number call kit Lets define kitwise XOR kits b bbmod kThe kitwise XOR base k number equal new number form take kitwise XOR corresponding kit the kitwise XOR decimal number b denote aoplus_k b equal decimal representation kitwise XOR base k representation b all number statement decimal specify when k 2 true version kitwise XOR bitwise XORYou hack criminal database Rockport Police Department RPD know Rap Sheet but order access require password you do not know sure lie 0 n1 inclusive so decide guess luckily try n time block system but system adaptive each time incorrect guess change password Specifically password guess x guess different number y system change password number z xoplus_k zy Guess password break system
0array
let fi denote minimum positive integer x x divisor iCompute sum_i1n fi modulo 1097 in word compute f1f2dotsfn modulo 1097
2string
you play permutation p length n lose Blair AlabamaLuckily remember information permutation more specifically remember array b length n b_i number indice j j p_j p_iYou array b want find permutation p however memory is not perfect constantly change value b learn for q second follow thing happen 1 x realize b_i equal x 2 need find value p_i if there s answer print it prove there s possible answer constraint problem Answer query remember array
1graph
you give tree consist n node you generate array tree mark node oneInitially node mark node equiprobably choose mark entire tree after node mark node equiprobably choose marked set unmarked node edge mark node it show process mark node tree the final array list node label order time node markedFind expect number inversion array generate tree aforementione processthe number inversion array number pair index j j a_i a_j for example array 4 1 3 2 contain 4 inversion 1 2 1 3 1 4 3 4
1graph
the Alices computer break can not play favorite card game to help Alice Bob want answer n question Initially Bob hold card number 0 leave hand right hand in ith question Alice ask Bob replace card leave right hand card number k_i Bob choose card change Bob replace exactly cardafter action Alice want number leave right card belong give segment segment leave right card different formally let number leave card x right card y then ith swap follow condition satisfied a_l le x le b_l a_r le y le b_riPlease determine Bob answer request if possible find way
2string
Lena economical girl Moscow so dad ask buy food trip country go good store PriceFixed here rule store the store infinite number item product all product price 2 ruble item for product discount experience buyer buy b_i item product type necessarily type future purchase ith product 50 discount buy item ith product 1 ruble Lena need buy n product purchase a_i item ith product help Lena calculate minimum money need spend optimally choose order purchase note want buy item product need
1graph
polycarp x red y blue candy use want gift set each gift set contain red candy b blue candy blue candy b red candy any candy belong gift sethelp Polycarp find large number gift set createfor example x 10 y 12 5 b 2 Polycarp gift set in set 5 red candy 2 blue candy in second set 5 blue candy 2 red candy in set 5 blue candy 2 red candy note example red candy Polycarp use gift set
1graph
polycarp n friend ith friend a_i candy Polycarps friend like different number candy in word want a_i to solve Polycarp perform follow set action exactly Polycarp choose k 0 le k le n arbitrary friend let choose friend index i_1 i_2 ldot i_k Polycarp distribute a_i_1 a_i_2 ldot a_i_k candy n friend during distribution a_i_1 a_i_2 ldot a_i_k candy choose new owner that n friend note candy give person own candy distribution process note number k fix advance arbitrary your task find minimum value kFor example n4 a4 5 2 5 polycarp follow distribution candy Polycarp choose k2 friend indice i2 4 distribute a_2 a_4 10 candy a4 4 4 4 candy person 3 note example Polycarp choose k1 friend redistribute candy end a_i equalFor datum n determine minimum value k with value k Polycarp able select k friend redistribute candy end number candy
2string
you connect undirected graph n node m edge the ith node value v_i target value t_iin operation choose edge j add k v_i v_j k integer in particular k negativeYour task determine possible finite number operation possibly zero achieve node v_i t_i
1graph
you game designer want obstacle course the player walk leave right you n height mountain select want arrange absolute difference height mountain small possible in addition want game difficult walk uphill flat hard walk downhill difficulty level number mountain 1 leq n h_i leq h_i1 h_i height ith mountain you do not want waste mountain model use from arrangement minimize h_1h_n find difficult if multiple order satisfy requirement find
2string
an array b length k call good arithmetic mean equal 1 more formally fracb_1 cdot b_kk1Note value fracb_1cdotsb_kk round for example array 1112 arithmetic mean 125 equal 1you give integer array length n in operation append nonnegative integer end array what s minimum number operation require array goodWe proof possible finitely operation
1graph
omkar recent follower Ajit enter Holy Forest Ajit realize Omkars forest n m grid 1 leq n m leq 2000 nonnegative integer since forest bless Omkar satisfy special condition for adjacent sharing cell absolute value difference number 1 if number cell strictly large 0 strictly great number cell adjacent Unfortunately Ajit fully worthy omkar power he see cell 0 if cell label 0 number equal 0 otherwise number nonnegative integerDetermine different assignment element exist special condition satisfy two assignment consider different exist cell number write assignment different since answer enormous find answer modulo 1097
1graph
2k team participate playoff tournament the tournament consist 2k 1 game they hold follow team split pair team 1 play team 2 team 3 play team 4 exactly order 2k1 game play phase when team lose game eliminate game result elimination team tie after 2k1 team remain if team remains declare champion 2k2 game play winner game 1 vs 2 play winner game 3 vs 4 winner game 5 vs 6 play winner game 7 vs 8 this process repeat team remainsfor example picture describe chronological order game k 3 let string s consist 2k 1 character describe result game chronological order follow s_i 0 team low index win ith game s_i 1 team great index win ith game s_i result ith game unknown team win game let fs number possible winner tournament describe string s a team possible winner tournament possible replace 1 0 way team championyou give initial state string s you process q query follow form p c replace s_p character c print fs result query
1graph
four player participate playoff tournament the tournament hold accord follow scheme player play second player fourth winner pair play final tournamentit know match player skill great win the skill ith player equal s_i skill level pairwise different ie identical value array sthe tournament call fair player high skill meet finalsdetermine give tournament fair
2string
Annie get bored win code contest farm unlimited rating today go farm potato insteadannie garden infinite 2D plane she n potatoe plant ith potato plant x_iy_i start point 0 0 Annie begin walk step travel unit right increase x y coordinate 1 respectively at point XY walk plant potato arbitrary point potato gun consume maxxxyy unit energy order plant potato xy find minimum total energy require plant potatonote Annie plant number potato point
2string
little Dormi receive histogram n bar height a_1 a_2 ldot a_n Christmas however play new histogram realize imperfection today want modify likingTo modify histogram Little Dormi able perform follow operation arbitrary number time Select index 1 le le n a_i0 assign a_i a_i1Little Dormi define ugliness score histogram perform number operation sum vertical length outline number operation perform and histogram perfect possible like minimize ugliness score modifying number operationshowever histogram large Little Dormi have trouble minimize ugliness score Little Dormis old brother help find minimal uglinessconsider follow example histogram 4 column height 4896 the blue region represent histogram red line represent vertical portion outline currently vertical length outline 44136 18 little Dormi modify histogram ugliness 18however Little Dormi apply operation column 2 twice column 3 result histogram height 4776 now total vertical length outline red line 431614 ugliness 14317 dollar it prove optimal
1graph
Vika decide trip Bertown she come Bertown kth day Vika want spend money hotel fortunately n friend live Bertown allow Vika stay house the ith friend tell Vika stay house l_ith day till r_ith day inclusivevika decide stay friend house help Vika determine maximum number day able stay Bertown
1graph
a frog currently point 0 coordinate axis Ox it jump follow algorithm jump unit right second jump b unit leave jump unit right fourth jump b unit leave onformally frog jump number time current jump jump current position x position xa jump current position x position xb your task calculate position frog k jumpsbut one thing you watch t different frog answer t independent query
1graph
you friend Ilya participate individual programming contest consist multiple stage a contestant 0 100 point inclusive stage independently contestantspoint receive contestant different stage form overall contest result suppose k stage contest complete for contestant k lfloor frack4 rfloor stage high score select score add this sum overall result contestant here lfloor t rfloor denote round t downFor example suppose 9 stage complete score 50 30 50 50 100 10 30 100 50 first 7 stage high score choose example stage 2nd 6th choose then overall result equal 50 50 50 100 30 100 50 430as n stage complete know point Ilya get stage however unknown stage hold you wonder small number additional stage result great equal Ilyas result theory find number
1graph
you give tree n node numerate 0 n1 for k 0 n inclusive count number unordere pair uv u neq v MEX node label short path u v include end point kThe MEX sequence integer smallest nonnegative integer belong sequence
0array
after reject 10100 datum structure problem Errorgorn angry Anton decide kill himantons DNA represent string contain character anton 4 distinct character Errorgorn change Antons dna string b permutation however anton body defend attack in 1 second body swap 2 adjacent character dna transform Antons body smart use minimum number movesTo maximize chance Anton die Errorgorn want change Antons dna string maximize time Antons body revert DNA but Errorgorn busy make data structure problem need help find good string b can help
2string
monocarp playing game assimilation IV in game manage great empire build city conquer new landsmonocarp empire n city in order conquer new land plans build Monument city the game turnbase Monocarp amateur build exactly Monument turnMonocarp m point map he d like control construct Monuments for point know distance city Monuments work follow way build city Monument control point distance 1 city Next turn Monument control point distance 2 turn distance 3 Monocarp build n Monuments n turns empire conquer point control MonumentMonocarp can not figure strategy turn choose city Monument randomly remain city city Monuments Monocarp want know point m conquer end turn number n Help calculate expect number conquer point
1graph
you give permutation consist n number 1 2 n permutation array element 1 n occur exactly onceYou perform follow operation choose subarray contiguous subsegment rearrange element way want but operation apply arrayfor example 2 1 4 5 3 want apply operation subarray a2 4 subarray contain element 2nd 4th operation array 2 5 1 4 3 example 2 1 5 4 3your task calculate minimum number operation describe sort permutation ascending order
1graph
William own flat central London he decide rent flat n day earn moneySince flat center city instantly get m offer form l_i r_i mean want book flat day l_i day r_i inclusive to avoid spend lot time figure profitable accept offer William decide develop algorithm the algorithm process offer arrive accept offer follow condition satisfied r_i l_i 1 ge x None day l_i r_i occupy previously accept offer William is not sure value x ask help for x 1 n wants calculate total number day flat occupy corresponding value assign x
2string
after William work day enjoy play favorite video gameThe game happen 2D world start turn 0 William pick cell game world spawn then turn William remain current location current location x y follow location x 1 y x 1 y x y 1 x y 1To accelerate movement game n fast travel tower ith tower locate location xa_i ya_i to able instantly travel tower location game world activate Activation tower happen moment player cell xa_i ya_i tower remain active entire gameWilliam know game m quest ith quest complete instantly location xb_i yb_i turn t_iWilliam wants find maximal number quest able complete optimally traverse game world
1graph
while trade favorite exchange trader William realize found vulnerability use vulnerability change value certain internal variable advantage to play decide change value internal variable a_1 a_2 ldot a_n a_1 a_2 ldot a_n for unknown reason number service variable numberWilliam understand action attract attention exchange security team number action exceed 5000 operation variable absolute value great 1018 William perform action type choose variable indice j j Perform assignment a_i a_i a_j perform assignment a_j a_j a_i William want develop strategy internal variable desire value
1graph
Nastia receive array n positive integer giftshe call array good 2 le le n take place gcda_i 1 a_i 1 gcdu v denote great common divisor GCD integer u vYou perform operation select different index j 1 le j le n neq j integer x y 1 le x y le 2 cdot 109 mina_i a_j minx y then change a_i x a_j yThe girl ask array good n operationsIt prove possible
2string
Dima overslept alarm clock suppose raise schoolDima wonder time come lesson to need know minimum time home schoolthe city Dima live rectangular field n time m size each cell j field denote number a_ij the number 1 mean passage cell prohibit the number 0 mean cell free Dima walk the number x 1 le x le 109 mean cell contain portal cost x a cell portal consider free from portal Dima portal time move portal j portal x y correspond sum cost a_ij a_xyin addition move portal Dima unoccupied cell adjacent time w in particular enter cell portal use itinitially Dima upperleft cell 1 1 school low right cell n m
1graph
you give array n integer Count number pair index j j a_j a_i j
2string
let positive integer n ordinary decimal notation digit for example 1 2 99 ordinary number 719 2021 ordinary numbersfor give number n find number ordinary number number 1 n
1graph
Alice Bob play game Alice get n treasure chest ith contain a_i coin m key jth sell Bob b_j coinsfirstly Alice put lock chest there m type lock lock jth type open jth key to lock type j ith chest Alice pay c_ij dollar Alice number different type lock chest possibly zeroThen Bob buy key Alice possibly possibly open chest open chest key lock ch Bobs profit difference total number coin open chest total number coin spend buy key Alice if Bobs profit strictly positive great zero win game Otherwise Alice win gameAlice want lock chest matter key Bob buy win Bob positive profit of course wants spend minimum possible number dollar buying lock help determine win game dollar spend lock
1graph
at foot Liyushan Mountain n tent carefully arrange provide accommodation willing experience joy approach nature tranquility night bright starry skythe ith tent locate point x_i y_i weight w_i a tent important x_i y_i you need remove tent remain important tent x y exist 3 tent x_1 y_1 x_2 y_2 x_3 y_3 condition true x_jx y_j yleq 1 j 1 2 3 tent form parallelogram rectangle side parallel xaxis please maximize sum weight tent remove print maximum value
1graph
you wander explorer space 2050 ConferenceThe explorer space view undirected weight grid graph size ntime m the set vertex j1le ile n 1le jle m two vertex i_1j_1 i_2 j_2 connect edge i_1i_2j_1j_21at step walk vertex connect edge current vertex on edge number exhibit since know exhibit edge contain x exhibit boredness increase xFor start vertex j answer follow question what minimum possible boredness walk j exactly k stepsYou use edge multiple time boredness edge count multiple time at step stay current vertex you change direction go edge before go start vertex j k step visit j freely
2string
the 2050 volunteer organize Run Chase rise Sun activity start Apr 25 730 runner complete 6 km trail Yunqi townthere n1 checkpoint trail they number 0 1 n a runner start checkpoint 0 finish checkpoint n no checkpoint skippable run checkpoint 0 checkpoint 1 checkpoint 1 checkpoint 2 Look picture note section clarificationbetween adjacent checkpoint m different path choose for 1le ile n run checkpoint i1 checkpoint runner choose exactly m possible path the length jth path checkpoint i1 b_ij 1le jle m 1le ile nto test trail m runner each runner run checkpoint 0 checkpoint n visit checkpoint every path pair adjacent checkpoint need run exactly runner if runner choose path length l_i checkpoint i1 1le ile n tiredness min_i1n l_i ie minimum length path takesplease arrange path m runner minimize sum tiredness
2string
give array length n k operation follow type choose 2 different element array add 1 subtract 1 second however element remain nonnegative operation what lexicographically small array obtainAn array x lexicographically small array y exist index x_iy_i x_jy_j 1 le j Less formally index differ x_iy_i
1graph
Baby Ehab piece Cut Stick array length n write he plan grab pair scissor follow pick range l r cut element a_l a_l 1 a_r range stick elements order array end multiple piece piece contain element element belong piece more formally partition sequence a_l a_l 1 a_r subsequence he think partition beautiful piece subsequence hold length x value occur strictly lceil fracx2 rceil time itHe do not pick range he s wonder q range l r minimum number piece need partition element a_l a_l 1 a_r partition beautifulA sequence b subsequence array b obtain delete possibly zero element note contiguous
1graph
an array call beautiful element array equalyou transform array follow step number time Choose indice j 1 leq ij leq n integer x 1 leq x leq a_i let source index j sink index Decrease ith element x increase jth element x the result value ith jth index a_ix a_jx respectively the cost operation x cdot ji now ith index long sink jth index long source the total cost transformation sum cost step 3for example array 0 2 3 3 transform beautiful array 2 2 2 2 total cost 1 cdot 13 1 cdot 14 5an array call balanced transform beautiful array cost transformation uniquely define in word minimum cost transformation beautiful array equal maximum costYou give array a_1 a_2 ldot a_n length n consist nonnegative integer your task find number balance array permutation give array two array consider different element position differ since answer large output modulo 109 7
1graph
you give array n n geq 2 positive integer integer p consider undirected weighted graph n vertex number 1 n edge vertice j ij add follow manner if gcda_i a_i1 a_i2 dot a_j mina_i a_i1 a_i2 dot a_j edge weight mina_i a_i1 a_i2 dot a_j j if i1j edge weight p j here gcdx y ldot denote great common divisor GCD integers x y Note multiple edge j condition true condition fail j edge verticesThe goal find weight minimum span tree graph
1graph
let define cost string s number index pair j 1 le j s s_i s_j s_i1 s_j1You give positive integer n k among string length n contain k character latin alphabet find string minimum possible cost if multiple string minimum cost find
1graph
there problem cactus NERC 2020 online round that s bad mistake judge decide fix you shall pass World Finals 2021 solve problem cactusA cactus connect undirected graph edge lie simple cycle intuitively cactus generalization tree cycle allow multiedge multiple edge pair vertex loop edge connect vertex allow cactus Cher get cactus she call cactus strong impossible add edge way remain cactus but Cher think cactus strong she wants add small possible number edge strong ieto create new cactus vertex original cactus subgraph new impossible add edge graph remain cactus Cher hire job so
0array
Yuu Koito Touko Nanami newlywed on wedding day Yuu gift Touko direct tree n node root 1 labeling DFS order tree every edge tree direct away rootafter call dfs1 follow algorithm return DFS order tree root 1 order 0a array length n function dfsu order order 1 au order v direct edge u v dfsvNote different DFS order give treeTouko like present decide play on day follow wedding day Touko perform procedure among directed edge u rightarrow v a_u a_v select edge u rightarrow v lexicographically small pair a_u a_v swap a_u a_vday pass wedding Touko forget date wed original labeling Fearing Yuu angry Touko decide ask derive piece information current labelingbee good friend need find number day pass wedding original labeling tree however chance Touko mess procedure result current labeling impossible obtain original labeling case inform Touko
2string
consider infinite triangle layer Lets number layer start triangle the kth layer triangle contain k point number leave right each point infinite triangle describe pair number r c 1 le c le r r number layer c number point layer from point r c direct edge point r1 c r1 c1 edge activate if r c edge point r1 c activate edge point r1 c1 activate Look picture well understand activate edge color black nonactivated edge color gray from point r_1 c_1 possible reach point r_2 c_2 path activate edge for example picture path 1 1 3 2 path 2 1 1 1initially point 1 1 for turn replace activate edge point r c that edge point r1 c activate instead edge point r1 c1 activate edge point r1 c1 instead edge point r1 c activate this action increase cost path 1 move current point follow activate edge this action increase cost path you give sequence n point infinite triangle r_1 c_1 r_2 c_2 ldot r_n c_n find minimum cost path 1 1 pass n point arbitrary order
1graph
you give string b consist lowercase latin letter you number follow operation order 0 length string great zero delete character string replace a_2 a_3 ldot a_n 0 delete character string replace a_1 a_2 ldot a_n1 b 0 length string b great zero delete character string b replace b b_2 b_3 ldot b_n b 0 delete character string b replace b b_1 b_2 ldot b_n1 Note operation string b emptyfor example ahello bicpc apply follow sequence operation delete character stre rightarrow aello bicpc delete character string b rightarrow aello bcpc delete character string b rightarrow aello bpc delete character stre Rightarrow aell bpc delete character string b rightarrow aell bp for give string b find minimum number operation string b equal Note string equal
1graph
you give mysterious language codename Secret 2021 available Custom test tab Find language write program output Note program write language
2string
inputthe input contain integer N M 1 le N le 1024 2 le M le 16 separate single spaceoutputoutput yes NOExamplesInput2 3OutputYESInput3 2outputnoinput33 16outputyesinput26 5outputno
1graph
a palindrome string read backward forward for example string z aaa aba abccba palindromes codeforce ab you hate palindrome déjà vuThere string s you insert exactly character s if possible create string palindrome find example Otherwise report impossiblefor example suppose s cbabc by insert create acbabc cababc cbaabc cbabac cbabca however cbaabc palindrome output option
2string
there grid n row m column every cell grid color blue yellowA coloring grid call stupid row exactly segment blue cell column exactly segment yellow cellsin word row blue cell blue cell row consecutive similarly column yellow cell yellow cell column consecutive an example stupid color Examples clever coloring the coloring miss blue cell second row second color yellow segment second column how stupid coloring grid two coloring consider different cell color differently
1graph
a sequence bracket call balanced turn valid math expression add character 1 for example sequence balance notyou give binary string s length n construct balanced bracket sequence b length n 1le ile n s_i1 a_ib_i s_i0 a_ine b_i if impossible report
2string
Alexey travel train unfortunately bad weather train move slow shouldAlexey take train railroad terminal Lets train start terminal moment 0 also let train visit n station number 1 n way Alexey destination station nAlexey learn train schedule n integer pair a_i b_i a_i expect time train arrival ith station b_i expect time departurealso information Alexey able calculate n integer tm_1 tm_2 dot tm_n tm_i extra time train need travel station 1 station formally train need exactly a_i b_i1 tm_i time travel station 1 station 1 b_0 moment train leave terminal equal 0the train leave station condition meet station leftlceil fracb_i a_i2 rightrceil unit time division ceiling current time ge b_i since Alexey spend energy prediction time delay help calculate time arrival station n
1graph
Vanya invent interesting trick set integerslet illusionist set positive integer S he name positive integer x then audience volunteer choose subset possibly S disclose illusionist the volunteer tell illusionist size choose subset and come trick illusionist guesses sum subset element exceed x the sum element subset consider 0Vanya want prepare trick public performance he prepare set distinct positive integer S Vasya want trick successful he call positive number x unsuitable can not sure trick successful subset viewer chooseVanya want count number unsuitable integer choose set SVanya plan try different set S he want write program find number unsuitable integer initial set S change set S Vanya q change set change follow type add new integer set S remove integer set S
1graph
you give string x y consist lowercase latin letter let s length string sLets sequence merging sequence consist exactly x zero exactly y one orderA merge z produce sequence follow rule a_i0 remove letter begin x append end z a_i1 remove letter begin y append end z two merging sequence b different position a_i neq b_ilet stre z chaotic 2 z z_i1 neq z_ilet slr 1 le l le r le s substre consecutive letter s start position l end position r inclusiveLet fl_1 r_1 l_2 r_2 number different merging sequence xl_1r_1 yl_2r_2 produce chaotic merge note nonempty substring x y consideredCalculate sum limits_1 le l_1 le r_1 le x 1 le l_2 le r_2 le y fl_1 r_1 l_2 r_2 Output answer modulo 998244353
1graph
you give string s consist character 0 1 let s length sYou ask choose integer k k 0 find sequence length k 1 le a_1 a_2 dots a_k le s a_i1 1 a_i 2 k the character position a_1 a_2 dot a_k remove remain character concatenate change order so word position sequence adjacentlet result string s s call sorted 2 s s_i1 le s_idoe exist sequence result string s sort
2string
Alice Bob go celebrate Christmas playing game tree present the tree n node number 1 n node r root there a_i present hang ith nodebefore begin game special integer k choose the game proceed follow Alice begin game move alternate turn current player choose node example depth k then player pick positive number present hang node let m 1 le m le a_i player place m presents kth ancestor let j ith node kth ancestor vertex vertex j descendant j difference depth j depth exactly k now number present ith node a_i decrease m correspondingly a_j increase m Alice Bob play optimally the player unable lose gameFor possible root tree find Alice Bob win gamenote the depth node tree root r define number edge simple path node r node the depth root r zero
2string
this hard version problem the difference version 0 leq k leq 20There array a_1 a_2 ldot a_n n positive integer you divide minimal number continuous segment segment number different position product perfect squareMoreover allow k operation division choose number array change value positive integerwhat minimum number continuous segment use change optimally
1graph
we define span tree graph BFS tree root vertex s node t short distance s t graph equal short distance s t span tree give graph define fxy number span tree graph BFS tree root vertex x y timeYou give undirected connect graph n vertex m edge Calculate fij j modulo 998244353
1graph
you give direct graph consist n vertex each direct edge arc label single character Initially graph emptyyou process m query each query type u v c add arc u v label c its guarantee arc u v graph moment u v erase arc u v its guarantee graph contain arc u v moment k find sequence k vertex v_1 v_2 dot v_k exist route v_1 v_2 dot v_k v_k v_k 1 dot v_1 write character route you ll stre you visit vertex number time
1graph
the Dogeforces company k employee each employee lowerlevel employee 2 subordinate lowerlevel employee subordinate each employee head company exactly direct supervisor the head company direct indirect supervisor employee it know dogeforce supervisor receive salary strictly subordinatesthe structure company secret know number lowerlevel employee pair lowerlevel employee salary common supervisor know supervisor supervisor minimum salary you restore structure company
1graph
three swimmer decide organize party swimming pool at noon start swim leave poolit take swimmer exactly minute swim entire pool come exactly b minute second swimmer c minute hence swimm leave pool 0 2a 3a minute start time second 0 b 2b 3b minute leave pool 0 c 2c 3c minutesYou came leave pool exactly p minute start swim Determine long wait swimmer arrive leave pool
1graph
a championship hold Berland n player participate the player number a_i a_i ge 1 tokensthe championship consist n1 game play accord follow rule game random player nonzero tokens select player token consider winner game case tie winner choose randomly win player take loser token the player nonzero tokens winner championshipAll random decision championship equally probable independentlyfor example n4 1 2 4 3 option game option game fourth player select the fourth player tokens take player token now 0 2 4 4 second game fourth player select they number token random way player winner now 0 2 8 0 game second player select the player token take second player token now 0 0 10 0 player declare winner championship championship winner receive personalized prize therefore judge want know advance player chance win ie nonzero probability win championship you ask find player
0array
you give integ n sequence n1 integer element 0 1you ask build string length n letter abcd a_i1 ith suffix string lexicographically small i1th suffix a_i0 ith suffix string lexicographically great i1th suffix you ask q query form 1 le le n 1 flip value a_i a_i0 set a_i 1 vice versa after query print number different string satisfy give constraint modulo 998244353
2string
a bracket sequence string contain character a regular bracket sequence shortly rbs bracket sequence transform correct arithmetic expression insert character 1 original character sequence for example bracket sequence regular result expression 11 111 bracket sequence you give stre s rbs you apply number operation string each operation follow type choose nonempty prefix s remove s s rbs for example apply operation follow 10 character remove choose contiguous nonempty substring s remove s s rbs for example apply operation follow character 7th 10th remove the operation 2 apply k time calculate maximum number operation apply s
1graph
you give positive great zero integer nYou represent n sum integer possibly negative consist one digits 1 for example 24 11 11 1 1 102 111 11 1 1 among possible representation find use minimum number one total
1graph
a big football championship occur soon n team compete pair team play exactly game otherThere possible outcomes game game result tie team 1 point team win game winning team get 3 point lose team get 0 point the score team number point gain game playedyou interested hypothetical situation team score end championship a simple example situation game result tie want minimize number tie wellyour task describe situation choose result game team score number tie minimum possible
2string
suppose living cat a b there n nap spot cat usually sleepyour cat like sleep like spot change nap spot hour cyclically Cat a change nap place order n n 1 n 2 dot 3 2 1 n n 1 dot in word hour spot n go decrease order cyclically Cat B change nap place order 1 2 3 dot n 1 n 1 2 dot in word hour spot 1 go increase order cyclically the cat b young strict hierarchy A b do not lie in word catsd like spot x a take place b move place order x n x 1 x n 1 Cat B follow order will not return skip spot x a free spot x 2 oncalculate cat B hour k
1graph
you give array length n find subarray alr length k large medianA median array length n element occupie position number lfloor fracn 12 rfloor sort element nondecrease order for example median1 2 3 4 2 median3 2 1 2 median2 1 2 1 1subarray alr contiguous array ie array a_la_l1ldotsa_r 1 leq l leq r leq n length r l 1
1graph
you give array integer b_1 b_2 ldots b_nAn array a_1 a_2 ldot a_n integer hybrid 1 leq leq n condition true b_i a_i b_i sum_j1i a_j find number hybrid array a_1 a_2 ldot a_n as result large print answer modulo 109 7
2string
you give matrix consist positive integer it n row m columnsconstruct matrix b consist positive integer it size follow condition meet 1 le b_ij le 106 b_ij multiple a_ij absolute value difference number adjacent pair cell cell share b equal k4 integer k ge 1 k necessarily pair pair we answer exist
1graph
this year Chunin Selection Exam hold Konoha take n ninjas name s_1 s_2 s_n all name distinct one exam stage consists fight participant this year rule determine ninjas fight follow ninjas j fight follow condition hold neq j s_j substre s_i k j s_j substring s_k s_k substre s_i a string substre string b obtain b deletion possibly zero character begin possibly zero character endyour task find fight go place year
2string
you given weight undirected graph n vertex q triple u v l triple u v vertex l positive integer an edge e call useful triple u v l path necessarily simple follow property u v endpoint path e edge path sum weight edge path do not exceed l please print number useful edge graph
1graph
Arkady playlist initially consist n song numerate 1 n order appear playlist Arkady start listen song playlist start song 1 the playlist cycle ie listening song Arkady continue listen beginningEach song genre a_i positive integer let Arkady finish listen song genre y genre nexttolast listen song x if operatornamegcdx y 1 delete listen song genre y playlist after continue listen normally skip deleted song forget song listen in word delete song can not delete song immediatelyHere operatornamegcdx y denote great common divisor GCD integer x yFor example initial song genre 5 9 2 10 15 playlist convert follow 5 9 2 10 15 5 9 2 10 15 5 2 10 15 operatornamegcd5 9 1 5 2 10 15 5 2 10 15 5 2 10 15 5 2 10 15 5 2 10 15 5 10 15 operatornamegcd5 2 1 5 10 15 5 10 15 the bold number represent play song Note song delete Arkady forget listen previous songsgiven initial playlist determine song eventually delete order song delete
1graph
you finally wake crazy dream decide walk clear head outside see house fence plain boring you d like repaint you fence consist n plank ith plank color a_i you want repaint fence way ith plank color b_iYouve invite m painter purpose the jth painter arrive moment j recolor exactly plank color c_j for painter choose plank recolor can not turn ie painter color exactly plankCan color b want if possible print painter plank paint
1graph
the great hero guard country Homer live the hero attack power a initial health value B there n monster hero the ith monster attack power a_i initial health value b_i the hero monster say live health value positive greater equal 1 say dead health value nonpositive equal 0in order protect people country hero fight monster hero dead monster dead in fight hero select arbitrary living monster fight suppose ith monster select health value hero ith monster x y fight respectively after fight health value hero ith monster xa_i yA respectively note hero fight monster oncefor safety people country tell great hero kill monster great hero dead killing monster
2string
in Homers school n student love club initially m club n student exactly club in word a_i student ith club 1 leq leq m a_1a_2dotsa_m nThe n student unfriendly day choose uniformly random n student get angry the student get angry follow thing with probability frac 1 2 leave current club create new club join there student new club create with probability frac 1 2 create new club in case change club new possibly club currently probability proportional number student formally suppose k club b_i student ith club 1 leq leq k student get angry he leave current club join ith club probability frac b_i n we note club student join student get angry join club probability 0 accord statementHomer wonder expect number day student club timeWe prove answer represent rational number frac p q gcdp q 1 therefore ask find value pq1 bmod 998244353 it show q bmod 998244353 neq 0 give constraint problem
2string
long time ago symmetric array a_1a_2ldotsa_2n consist 2n distinct integer Array a_1a_2ldotsa_2n call symmetric integer 1 le le 2n exist integer 1 le j le 2n a_i a_jFor integer 1 le le 2n Nezzar write integer d_i equal sum absolute difference a_i integer ie d_i sum_j 12n a_i a_jnow million year pass Nezzar barely remember array d totally forget Nezzar wonder exist symmetric array consist 2n distinct integer generate array d
1graph
you give n pattern p_1 p_2 dot p_n m string s_1 s_2 dot s_m each pattern p_i consist k character lowercase latin letter wildcard character denote underscore all pattern pairwise distinct each string s_j consist k lowercase Latin lettersA string match pattern b 1 k b_i wildcard character b_ia_iYou ask rearrange pattern way pattern jth string match pmt_j you allow leave order pattern unchangedcan perform rearrangement if print valid order
1graph
Polycarp find street array n elementsPolycarp invent criterion beauty array he call array beautiful follow condition meet different pair index ne j a_i divisible a_j a_j divisible a_i for example n5 a7 9 3 14 63 array beautiful i4 j2 condition meet n3 a2 14 42 array beautiful n4 a45 9 3 18 array beautiful i1 j4 condition meet Ugly array upset Polycarp want remove element array beautiful Help Polycarp determine small number element remove array beautiful
1graph
you give binary square matrix b size n time n a matrix call binary element equal 0 1 you follow operation matrix arbitrary number times 0 vertical xor you choose number j 1 le j le n 1 le le n follow a_i j a_i j oplus 1 oplus operation xor exclusive horizontal xor you choose number 1 le le n j 1 le j le n follow a_i j a_i j oplus 1 Note element matrix change operationFor example n3 matrix beginpmatrix 1 1 0 0 0 1 1 1 0 endpmatrix then follow sequence operation show example transformation vertical xor j1 beginpmatrix 0 1 0 1 0 1 0 1 0 endpmatrix horizontal xor i2 beginpmatrix 0 1 0 0 1 0 0 1 0 endpmatrix vertical xor j2 beginpmatrix 0 0 0 0 0 0 0 0 0 endpmatrix check sequence operation matrix equal matrix b
1graph