版本比较
模板函数
正文
增加 1826 行删除 2916 行
112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879480818283849858687888914909192939440 行未改动1351361371381391401411421434 行未改动1481491501517576777879808182838485868788899015215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119292939495969798991931941951961971981992002012022031011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361372042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462471391401412482492502512522532542552562572582592602612622632642652662672682692702712722732741431442752762772782792802811501512822832842851531541552862872882892902912922932942951622962972982993003013023031703041723053063073083092 行未改动3123133143151833163173183191871881893203213223233243253262 行未改动3293303313322003333343353363372 行未改动3403413423432112122132142152162172182192202212222232242253443453463473483493503513523533543553563573583593603613626 行未改动3693703713722402412423733743753762442452463773783793803813823833842523853862542552562572582592602612623873883893903913923933943953963973982662673994004014024034042 行未改动4074084094102782794114124134144154164174182864194202884214224234242924254264274282962974294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584593083094604614624634644653143154664674684694704713203214724734744754764774783274794804814824834843334853353363374864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705713435725735745755763483493503513523533543553563573583595775785795805815825835845855865875885895905915923643653663673683693703715935945955965975985996006016023746036043763773783793803813823836056066076086096106116126136146156169 行未改动6266276286294016306316326336347 行未改动64264364464541764664741942064864965042265165242442542642765365465565665742943043165865966066143366266366443666566643843944044144244344444544644744866766866967067167267367467567667767845067968045245345445545645745845946068168268368468568668768868969046246369169269346546646746846947047147269469569669769869970070170247447547647747847948048148248348448548648748848949049149249349470370470570670770870971071171271371471571671771871972072172272372449649772572672749950050150272872973073173250450550650750850951051173373473573673773873974074174274351574474574674774874975075175275352552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555675475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778856056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259378979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282359582482582682759960060160260360482882983083183283383483560760883683783883984084161361461561661761861962062162284284384484584684784884985085185285385485562785685785885963163263363463563663763863964064164286086186286386486586686786886987087187287387464687587687787887935 行未改动91591691791869069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082191982392092192292392410 行未改动935936937938842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110829399409419429431084108510861087108810891090109110921093109410951096109710981099110011011102110311049449459469471106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487948148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715389499509511540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573952157515769539549551578157995615811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161395795895916151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829960961962963964965966183718381839184018419679689699709719729731844974975976977978979980981982185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882983984985986987988989990991992993994995996188499799899918871888188918901891189210001001100210031004100510061007100810091010101110121013101410151016101710181019189418951020102110221023102410251026102710281900102910301902190319041031103210331034103510361908190919101037103810391040104110421914191519161043104410451046104710481920104910501051105210533 行未改动10571058105910601932106110621063106410651937193819391940194119421943194410661067106810691070107110721073107410751076194819491950195119521953195419551077107810791080108110821083108410851086108719591960196119621963196419651966196719681969108810891090109110921093109410951096109710981099110011011973110211031975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320041104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114120131142114320152016201720182019202020212022202320242025202620272028114411451146114711481149115011511152115311541155115611571158115911601161116211631164116520371166116711681169117010 行未改动11811182118311842056118511862058205920602061206220632064206520662067206820692070207120722073207420752076207711871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209208120822083208420852086208720882089121012111212121312141215121612171218121912201221209312221223122412251226122712281229123012312103210421052106123212331234123512361237123812391240124121131242124312441245124612471248211921202121212221231249125012511252125312541255125612571258212912591260126112621263213412641265126621371267126812692140127012712142127212731274127512761277214812781279128012811282128312842155128512861287128812897 行未改动129712981299130021711301130213031304130521761306130721782179218021812182218321842185218613081309131013111312131313141315131613171318131921902191219221932194219521961320132113221323132413251326132713281329133022011331133213331334133511 行未改动13471348134913502221135113521353135413558 行未改动136413651366136722381368136922401370137113721373137410 行未改动138513861387138822591389139013911392139322641394139522662267139613971398139914002 行未改动140314041405140622781407140814091410141114122284141314141415141614172 行未改动142014211422142322952296142414251426142714281429143020 行未改动14511452145314542325145514562327145714581459146014611462146314641465146623371467146823392340234114691470147114721473147414758 行未改动148414851486148723582359148814891490149114921493236414941495149614971498149923701500150115022373150315041505150615071508150923801510151115121513151412 行未改动15271528152915302401153115321533153415353 行未改动153915401541154224131543154415451546154715482419242024212422154915502424155115521553242715541555155615571558243224332434155915601561156215639 行未改动15731574157515762452157715781579158015812457158215831584158515862462246324642465246624672468158715881589159015911592159315941595159615971598247424752476247715991600160116021603160416052481248224832484248524862487248824892490249124922493249424952496249716061607160816091610161116121613161416151616161716181619162016211622162316241625250116261627162816291630163116321633163425101635163616371638251425152516251716391640164116421643164425201645164625222523164716481649165016511652252825292530253125322533253416531654165516561657165816591660166116621663166425402541254225431665166616671668166916701671254725482549255025512552167216731674167516761677167816791680168125572558255916821683168416851686168716881689169016912567169216931694169516966 行未改动17031704170517062582258317071708170917101711171215 行未改动17281729173017312607173217331734173517367 行未改动1744174517461747262317481749175017511752175326291754175517561757175814 行未改动177317741775177626522653265426552656265726582659266017771778177917801781178217831784178517861787178826642665266626672668266926702671178917901791179217931794179517961797179817992675267626772678267926802681268226832684268526862687268826892690269126922693269418001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822269826992700270127022703182318241825182618271828182918301831183227081833183418351836183759 行未改动189718981899190027761901190219031904190546 行未改动1952195319541955283119561957195819591960196119622838283928402841284228432844284528462847196328492850285128521964196519661967196819691970285628572858285928602861286228632864286528662867197119721973197419751976197719781979198019811982198319841985198619872873198819891990199119921993287928802881288228832884288528862887288819942890289128922893199519961997199819992000200128972898289929002901290220022003200420052006200720082009201020115 行未改动201720182019202029162021202220232919202429212922292329242925292629272928292929302931202529332934293529362026202720282029203020312032203318 行未改动2052205320542055205629632964205720582059206020612062296929702971297229732974297529762977297820632980298129822983206420652066206720682069207029872988298929902991299229932994299529962997299820712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209730023003300430053006300730083009301020982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214230152143214421452146301930202147214821492150215130243025215221532154215521563029215721582159216021612162216321642165303830393040304130423043304430453046304730483049305030513052305330543055216621672168216921702171217221732174217521762177217821792180218121822183218421852186218730602188218921903063219121922193219421954 行未改动2200220122022203307622042205220622072208221 行未改动全部展开243024312432243333062434243524362437243866 行未改动250525062507250833812509251025112512251325142515251633892517251825192520252120 行未改动25422543254425453418254625472548254925508 行未改动2559256025612562343525632564256525662567190 行未改动全部展开275827592760276136342762276327642765363827662767276827692770366 行未改动全部展开31373138313931404013314131423143314431453146314740203148314931503151315253 行未改动32063207320832094082321032113212321332143215321640893217321832193220409332213222322332243225322632273228322932304103323132323233323432357 行未改动32433244324532464119324732483249325032515 行未改动32573258325932604133326132623263326432653 行未改动32693270327132724145414641474148414941504151415232733274327541544155415641573276327732783279328041594160416141624163416441654166416741684169328132823283328432854171417241734174417541764177417841794180328632873288328932903291329232933294329532963297418341844185418641874188418932983299330033013302330333043305330633073308330933103311419241934194419541964197419841994200420142023312331333143315331633173318331933204204420542064207420842094210421142124213332133223323332433253326332733283329333033313332421642174218421933333334333533363337333833393340422142224223422442254226422742284229423042314232423333413342334333443345334633473348334933503351335233533354423633553356335733583359497 行未改动全部展开3857385838593860474238613862386338643865321 行未改动全部展开4187418841894190507241914192419341944195109 行未改动全部展开4305430643074308519043094310431143124313519543144315431643175199431843194320432152035204520552065207520852095210521152124322432343244325432643274328432943304331433243334334521652175218521943354336433743384339434043415223522452254342434343444345434643475229523052315232523352345235523652375238434843494350435143524353435443554356435743584359436052425243524452455246524743614362436343644365436643674368436952515252525352545255525652575258525952605261526252635264437043714372437343744375437643774378437943804381438243834384438543865268526952705271527252735274527552765277527843874388438943904391439243934394439543964397439843994400528252834401440244034404528652875288528944054406440744084409441044115293529452955296529752985299441244134414441544164417441844194420442153035304530553065307530853094422442344244425442644274428442944304431531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753384432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446053424461446244634464446516 行未改动44824483448444855367536853695370537153725373537453755376537753785379538053815382538344864487448844894490449144924493449444954496449744984499450045014502450353855386538753885389539053915392539353945395539653974504450545064507450845094510451145124513451445154516451745184519452037 行未改动455845594560456154435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654674562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459013 行未改动460446054606460754895490549154925493549454955496549754985499550055015502550355044608460946104611461246134614461546164617461846194620462146224623462455064625462646274628462966 行未改动469646974698469955815582558355845585558655875588558955905591559255934700470147024703470447054706470747084709471047114712471347145596559755985599560047154716471747184719472047214722472312 行未改动4736473747384739562156225623562456255626562756285629563056315632474047414742474347444745474647474748474947504751475247534754475535 行未改动4791479247934794567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257134795479647974798479917 行未改动4817481848194820573948214822482348244825482648274828482948305749575057515752483148324833483448354836483757565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579448384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487957985799580058015802580358045805580658074880488148824883488448854886488748884889489048914892581158125813581458155816581748934894489548964897489848994900490149025821582258235824582558265827582858295830490349044905490649074908490949104911491249134914491558345835583658375838583958405841584258434916491749184919492049214922492349244925492649274928584758485849585058515852585358545855585658575858585958605861586258634929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139238 行未改动全部展开53785379538053816112538253835384538561165386538761186119612061216122612361246125612661276128538853895390539153925393539453955396539753985399540061315401540261336134613561366137613861396140614161426143540354045405540654075408540954105411541254135414541561465416541761486149615061516152615361546155615661576158615961606161616261636164616561665418541954205421542254235424542554265427542854295430543154325433543454355436543754386169543954406171617261736174617561766177617861796180544154425443544454455446544754485449545054515452618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454756319632063216322632363246325547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754986327632854995500550155026330633163326333633455035504550555065507550855095510551155126336551355145515551655175518551955205521633863396340634163426343634463456346634763486349635063516352635355225523552455255526552755285529553063556356635763586359636063616362636363646365636663676368636955315532553355345535553655375538553963716372637363746375637663776378637963805540554163826383638463856386638763886389639063916392639363946395639663975542554355445545639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765685546554755485549657065716572555055515552657465756576657765786579658065816582658365846585658665876588658965905553555455555556659365946595659665976598659955575558555955606601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066815561556255635564556566846685668666876688556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592109 行未改动全部展开57025703570457055706570757085709571057115712571357145715571657175718[](https://www.luogu.com.cn/article/xjmzumm3/edit "编辑:此操作仅作者有效") [](https://blog.csdn.net/cyx012113?type=blog "作者 CSDN") [](https://www.luogu.com.cn/user/1099138 "作者主页")**注意:文章内容量较大,网页内存占用可能达到数 MB。由于浏览器性能原因,渲染耗时可能较长。**
# Tips> Tips:> - [ ] 你数组开小了吗?> - [ ] 你 MLE 了吗?> - [ ] 你觉得是贪心,是不是该想想 dp?> - [ ] 一个小时没调出来,是不是该考虑换题?> - [ ] 打 cf 不要用 umap!!!> > 记住,Rating 是身外之物。> > 该冲正解时冲正解!> > Problem:> > 如果你会:> - [ ] 取模取了吗?> - [ ] 算法对拍了吗?> - [ ] 有没有保留小数据的暴力?> - [ ] 有没有清空?> - [ ] 精度够吗?> - [ ] 时间复杂度真的正确嘛?> - [ ] 会不会炸空间?> - [ ] 最大数据会不会炸?> - [ ] 自己造数据!> > 如果你不会:> - [ ] 有没有想最低分的 dp?dp 也是一种暴力> - [ ] 会不会写暴力分?> - [ ] 暴力能否优化?> - [ ] 暴力打表看看有没有非常明显的规律,有的黑题的规律就是 `cout << N * N`;> - [ ] 能否分块暴力?> - [ ] 有没有想最低分的 dp?> - [ ] 那个 dp 能否优化?> - [ ] 不要往深的地方思考,想浅一点多想点。> > 冷静冷静再冷静!> > 对拍对拍再对拍!:::align{right}——[$\bf\sf\color{#9d3dcf}{Yuneko}$](https://www.luogu.com.cn/user/820056 "小 Y | 快乐学习,认真刷题,努力进步!")[$\,\bf\sf\small\colorbox{#9c3dcf}{\color{white}{小Y}}$](https://help.luogu.com.cn/manual/luogu/account/user-tag):::> Things to check> - [ ] int overflow or need for long long> - [ ] recursion/array/binary search/dp/loop bounds> - [ ] precision> - [ ] special cases (n=1, bounds)> - [ ] delete debug statements> - [ ] initialize (especially multi-tests)> - [ ] = or ==, n or m, ++ or --, i or j, > or >=, < or <=, - or => - [ ] keep it simple and stupid> - [ ] do not delete, use // instead> - [ ] operator priority> - [ ] is there anything extra to output?> - [ ] if you don't know where the bug is, try to clear some parts of the code> and check each part separately.> - [ ] ...> > 需要检查的事项> - [ ] int 溢出或需要 long long> - [ ] 递归/数组/二分查找/动态规划/循环边界> - [ ] 精度> - [ ] 特殊情况 (n=1, 边界)> - [ ] 删除调试语句> - [ ] 初始化 (尤其是多组测试)> - [ ] = 还是 == , n 还是 m , ++ 还是 -- , i 还是 j , > 还是 >= , < 还是 <= , - 还是 => - [ ] 保持简单且直接> - [ ] 不要删除,用 // 注释掉> - [ ] 运算符优先级> - [ ] 有没有多余需要输出的内容?> - [ ] 如果不知道 bug 在哪里,试着注释掉部分代码,> 并分别检查每个部分。> - [ ] ...:::align{right}——[$\bf\sf\color{#3498db}{sszcdjr}$](https://www.luogu.com.cn/user/820056 "月亮好闪,拜谢月亮!"):::# 预处理 ## 主函数模板```cpp```cpp line-numbers#include <bits/stdc++.h>using namespace std;
signed main() { return 0;}```## 主函数模板(加强版)```cpp```cpp line-numbers#define _USE_MATH_DEFINES#include <bits/stdc++.h>#include <bits/extc++.h>//#define int long long40 行未改动#define IO ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)#define R return 0using namespace std;using namespace __gnu_pbds;using namespace __gnu_cxx;
const ll N = 5e5 + 2, LN = __lg(N) * 3 + 2, MN = 1e2 + 2, inf = INT_MAX;const ll dmax = INT_MAX, dmin = INT_MIN, mmax = 0x7f, minf = 0x7f7f7f7f;const ll lmax = LLONG_MAX, lmin = LLONG_MIN, ulmax = ULLONG_MAX;4 行未改动 return 0;}```## 指令集优化```cpp#define __AVX__ 1#define __AVX2__ 1#define __SSE__ 1#define __SSE2__ 1#define __SSE2_MATH__ 1#define __SSE3__ 1#define __SSE4_1__ 1#define __SSE4_2__ 1#define __SSE_MATH__ 1#define __SSSE3__ 1#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")#include <immintrin.h>#include <emmintrin.h># 卡常## Tips- [ ] 大炮打蚊子?把线段树当树状数组用?- [ ] 指针型数据结构改为数组型?(例如线段树)- [ ] 关同步流 / 快读快写- [ ] 避免除法和取模- [ ] 分块的块大小是否合理?(例如带修莫队板子,块大小需要为 $n^{\frac{2}{3}}$ 才可以,$\sqrt{n}$ 过不了)- [ ] 试试 C++ 14 (GCC 9),很多卡常的题换上就过了,据说“常数 $\times 0.7$”。- [ ] 运算能二进制的改成二进制(例如线段树 tr[pos << 1] tr[pos << 1 | 1])- [ ] 减少函数传参- [ ] 评测机波动?- [ ] endl 换成 `\n`- [ ] 数组开太大?改小 按照数组大小清空?memset?按需清空- [ ] 必须开 long long?能否开 short?- [ ] STL 优化: - map -> gp_hash_table(在 pbds 里) - vector?扩容时耗时巨大 -> 数组 - unordered_map -> map(被卡?)- [ ] 厌氧?- [ ] 火车头?(例如:指令集优化,fread,编译优化,请勿滥用)- [ ] i++ 改成 ++i- [ ] 无符号整数更快?- [ ] 递归函数改成非递归- [ ] 循环展开?(费手,不推荐)## 快读板子```cpp line-numbersint read() { // 快读 int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * f;}```## 编译设置```cpp#pragma GCC optimize(2)#pragma GCC optimize("Ofast")#pragma GCC optimize("inline","fast-math","unroll-loops","no-stack-protector")#pragma GCC diagnostic error "-fwhole-program"#pragma GCC diagnostic error "-fcse-skip-blocks"#pragma GCC diagnostic error "-funsafe-loop-optimizations"## 快写板子```cpp line-numbersvoid print(int x) { // 快写 if (x < 0) { putchar('-'); x = -x; } if (x > 9) print(x / 10); putchar(x % 10 + '0');}```## 头文件大全```cpp#include <algorithm>#include <bitset>#include <cctype>#include <cerrno>#include <clocale>#include <cmath>#include <complex>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <deque>#include <exception>#include <fstream>#include <functional>#include <limits>#include <list>#include <map>#include <iomanip>#include <ios>#include <iosfwd>#include <iostream>#include <istream>#include <ostream>#include <queue>#include <set>#include <sstream>#include <stack>#include <stdexcept>#include <streambuf>#include <string>#include <utility>#include <vector>#include <cwchar>#include <cwctype>## 指令集优化```cpp line-numbers#pragma GCC target("mmx,sse,sse2,sse3,ssse3") // 基础SSE#pragma GCC target("sse4.1,sse4.2,popcnt,lzcnt") // SSE4#pragma GCC target("avx,bmi,bmi2,f16c,fma,fma4,xop") // AVX#pragma GCC target("avx2,avx512f,avx512cd") // AVX2/AVX512
#include <immintrin.h> // 主头文件(包含所有)#include <x86intrin.h> // 额外x86内在函数
#ifdef __AVX512F__ #define SIMD_WIDTH 512 #define SIMD_ALIGN 64 #define simd_float __m512; #define simd_double __m512d; #define simd_int __m512i; #define SIMD_AVAILABLE 1#elif __AVX2__ #define SIMD_WIDTH 256 #define SIMD_ALIGN 32 #define simd_float __m256; #define simd_double __m256d; #define simd_int __m256i; #define SIMD_AVAILABLE 1#elif __AVX__ #define SIMD_WIDTH 256 #define SIMD_ALIGN 32 #define simd_float __m256; #define simd_double __m256d; #define simd_int __m256i; #define SIMD_AVAILABLE 1#elif __SSE4_2__ #define SIMD_WIDTH 128 #define SIMD_ALIGN 16 #define simd_float __m128; #define simd_double __m128d; #define simd_int __m128i; #define SIMD_AVAILABLE 1#else #define SIMD_WIDTH 0 #define SIMD_ALIGN 8 #define SIMD_AVAILABLE 0#endif```## 开启 O3 优化```cpp#pragma GCC optimize(3)## 编译设置(洛谷等 OJ 限制使用 `#pragma GCC optimize`)```cpp line-numbers#pragma GCC optimize("Ofast,unroll-loops,inline,fast-math,O3")#pragma GCC optimize("unsafe-math-optimizations,finite-math-only")#pragma GCC optimize("no-signed-zeros,no-trapping-math,associative-math")#pragma GCC optimize("no-stack-protector,omit-frame-pointer")#pragma GCC optimize("branch-target-load-optimize2")#pragma GCC optimize("btr-bb-exclusive,predictive-commoning,crossjumping")#pragma GCC optimize("hoist-adjacent-loads,gcse,aggressive-loop-optimizations")#pragma GCC optimize("tree-vectorize,tree-loop-if-convert,tree-loop-distribution")#pragma GCC optimize("tree-loop-im,tree-loop-ivcanon,tree-loop-linear")#pragma GCC optimize("tree-loop-optimize,prefetch-loop-arrays,peel-loops")#pragma GCC optimize("move-loop-invariants,inline-small-functions")#pragma GCC optimize("inline-functions-called-once,early-inlining,ipa-sra")#pragma GCC optimize("tree-bit-ccp,tree-ccp,if-conversion,if-conversion2")#pragma GCC optimize("branch-probabilities,reciprocal-math,modulo-sched")#pragma GCC optimize("modulo-sched-allow-regmoves,selective-scheduling")#pragma GCC optimize("selective-scheduling2,graphite-identity,loop-nest-optimize")#pragma GCC optimize("loop-interchange,loop-strip-mine,loop-block")#pragma GCC optimize("ipa-pta,ipa-cp")#pragma GCC optimize("ipa-cp-clone")
// 消除运行时信息#pragma GCC diagnostic ignored "-Wunused-parameter"#pragma GCC diagnostic ignored "-Wunused-variable"#pragma GCC diagnostic ignored "-Wsign-compare"```## 取消 cin、cout 缓存```cpp## 关闭同步流```cpp line-numbers#include <fstream>
ios::sync_with_stdio(0);cin.tie(0), cout.tie(0);```## 手写 Rand```cpp# 数学操作## 随机数```cpp line-numbersunsigned long long get_seed() { auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count()); auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count());}
mt19937_64 mt(get_seed());
long long Rand(long long mod) { if (mod <= 0) return 0; long long t = 0; while (t <= mod) t += mt() % 2, t <<= 1; while (t <= mod) t |= mt() % 2, t <<= 1; return (t % mod + mt() % 2) % mod;}
long long Rand(long long l, long long r) { return l + Rand(r - l);}```# 数学操作## 判断质数```cpp```cpp line-numbersbool Ip(int n) { if (n < 2) return false; if (n == 2) return true; for (int i = 2;i * i <= n;i++) {2 行未改动 return true;}```## 判断质数(Miller Rabin)```cpp```cpp line-numbersconst int test_time = 10;
unsigned long long get_seed() { auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count()); auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count());}
mt19937_64 mt(get_seed());
2 行未改动 while (t <= mod) t += mt() % 2, t <<= 1; return (t % mod + mt() % 2) % mod;}
int qp(int a, int b, int mod) { // 快速幂int qp(int a, int b, int mod) { int ans = 1; while (b) { if (b & 1) ans = (ans * a) % mod; b >>= 1;2 行未改动 return ans;}
bool miller_rabin(int n) { if (n < 3 && (!n & 1)) return n == 2; int a = n - 1, b = 0; while (a % 2 == 0) a >>= 1, b++; // test_time 为测试次数,建议设为不小于 10 的整数以保证正确率 // 但也不宜过大,否则会影响效率 for (int i = 1, j;i <= test_time;i++) { int x = Rand(n - 2) + 2, v = qp(x, a, n); if (v == 1) continue; for (j = 0;j < b;j++) { if (v == n - 1) break; v = v * v % n; } if (j >= b) return 0; } return 1; if (n < 3 && (!n & 1)) return n == 2; int a = n - 1, b = 0; while (a % 2 == 0) a >>= 1, b++; // test_time 为测试次数,建议设为不小于 10 的整数以保证正确率 // 但也不宜过大,否则会影响效率 for (int i = 1, j;i <= test_time;i++) { int x = Rand(n - 2) + 2, v = qp(x, a, n); if (v == 1) continue; for (j = 0;j < b;j++) { if (v == n - 1) break; v = v * v % n; } if (j >= b) return 0; } return 1;}```| test_time(测试次数) | 错误概率上限 | 正确率下限 || :----------: | :----------: | :----------: |6 行未改动| 20 | $(4^{-20} \approx 9.09 \times 10^{-13}) (\approx 0.000000000091\%)$ | $\approx 100%$ |
建议:不小于 $10$ 即可。## 输出因数```cppvoid of(int n) { // 输出因数 if (n < 1) return;```cpp line-numbersvoid of(int n) { if (n < 1) return; if (n == 1) { cout << "1" << endl; return; } cout << "1" << endl; return; } for (int i = 1;i <= n;i++) if (n % i == 0) cout << i << endl;}```## 分解质因数```cpp```cpp line-numbersvector <int> Gif(int n) { vector <int> result; for (int i = 2;i * i <= n;i++) { if (n % i == 0) { while (n % i == 0) n /= i; result.push_back(i); } } if (n != 1) result.push_back(n); return result; vector <int> result; for (int i = 2;i * i <= n;i++) { if (n % i == 0) { while (n % i == 0) n /= i; result.push_back(i); } } if (n != 1) result.push_back(n); return result;}```## 倒转数```cppint rv(int n) { // 反转```cpp line-numbersint rv(int n) { int t = 0; while (n > 0) { t *= 10; t += n % 10;2 行未改动 return t;}```## 阶乘```cppint fact(int n) { // 阶乘```cpp line-numbersint fact(int n) { int ans = 1; for (int i = 2;i <= n;i++) ans *= i; return ans;}```## 排列组合```cpp```cpp line-numbersint C(int n, int m) { return fa(n) / fa(m) / fa(n - m); return fact(n) / fact(m) / fact(n - m);}
int A(int n, int m) { return fa(n) / fa(n - m); return fact(n) / fact(n - m);}```## 快速幂```cppint qp(int a, int b, int mod) { // 快速幂```cpp line-numbersint qp(int a, int b, int mod) { int ans = 1; while (b) { if (b & 1) ans = (ans * a) % mod; b >>= 1; a = (a * a) % mod; } return ans;}```## 龟速乘```cpp line-numbersint sm(int a, int b, int mod) { int ans = 1; while (b) { if (b & 1) ans = (ans + a) % mod; b >>= 1; a = (a + a) % mod; }}```## 快速乘```cpp line-numbersint qm(int a, int b, int mod) { int c = a * b - ((long double)a / mod * b + 0.5L) * mod; if (c < 0) c += mod; return c + mod;}```## 勾股定理```cppdouble pt(double a, double b) { // 勾股定理```cpp line-numbersdouble pt(double a, double b) { return sqrt(pow(a, 2) + pow(b, 2));}```## 两点距离```cppdouble dist(double a1, double a2, double b1, double b2) { // 两点距离```cpp line-numbersdouble dist(double a1, double a2, double b1, double b2) { return sqrt(pow(fabs(a1 - b1), 2) + pow(fabs(a2 - b2), 2));}```## 海伦-秦九韶公式```cppdouble s(double a, double b, double c) { // 海伦-秦九韶公式```cpp line-numbersdouble s(double a, double b, double c) { double p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c));}```## 线性逆元```cpp```cpp line-numbersint n, p, inv[N], factinv[N];
signed main() { cin >> n >> p; factinv[1] = inv[1] = 1; cout << 1 << endl; for (int i = 2;i <= n;i++) { inv[i] = 1 * (p - p / i) * inv[p % i] % p; cout << inv[i] << endl; factinv[i] = 1 * factinv[i - 1] * inv[i] % p; inv[i] = (p - p / i) * inv[p % i] % p; factinv[i] = factinv[i - 1] * inv[i] % p; } return 0;}```## 扩展欧几里得(Exgcd)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) { if (!b) { x = 1; y = 0; return a; } int r = exgcd(b, a % b, x, y); int t = x; x = y; y = t - a / b * y; return r;}```## 中国剩余定理(CRT)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) { if (!b) { x = 1; y = 0; return a; } int r = exgcd(b, a % b, x, y); int t = x; x = y; y = t - a / b * y; return r;}
int n, a[N], b[N], ans = 1, s;
cin >> n;for (int i = 1;i <= n;i++) { cin >> a[i] >> b[i]; ans *= a[i];}for (int i = 1;i <= n;i++) { int k = ans / a[i], x, y; exgcd(k, a[i], x, y); s = s + k * b[i] * x % ans;}
cout << (s + ans) % ans << endl;```## 扩展中国剩余定理(ExCRT)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) { if (!b) { x = 1; y = 0; return a; } int r = exgcd(b, a % b, x, y); int t = x; x = y; y = t - a / b * y; return r;}
int n, X = 1, Y, a, b, ans = 1, s;
cin >> n;for (int i = 1;i <= n;i++) { cin >> a >> b; int x, y, g = exgcd(a, b, x, y); if ((Y - b) % g != 0) { cout << -1 << endl; return 0; } int u = x * (Y - b) / g; Y = Y - X * u; X = X * (a / g); Y = (Y % X + X) % X;}cout << (Y % X + X) % X << endl;```## 手写根号```cpp```cpp line-numbers#define exp 0.000001
// 二分法 double binsearch_sqrt(int m) { if (m <= 1) return m; double last = 0; double start = 0; double end = m; double mid = (start + end) / 2; while (abs(last - mid) > exp) { if (mid * mid > m) end = mid; else start = mid; last = mid; mid = (start + end) / 2; } return last; if (m <= 1) return m; double last = 0; double start = 0; double end = m; double mid = (start + end) / 2; while (abs(last - mid) > exp) { if (mid * mid > m) end = mid; else start = mid; last = mid; mid = (start + end) / 2; } return last;}
// 牛顿迭代法double newton_sqrt(int m) { double last = m; double ans = m; ans = (ans + m / ans) / 2; while (abs(ans - last) > exp) { last = ans; ans = (ans + m / ans) / 2; } return ans; double last = m; double ans = m; ans = (ans + m / ans) / 2; while (abs(ans - last) > exp) { last = ans; ans = (ans + m / ans) / 2; } return ans;}
// 必须使用float而不能用double // 神秘做法:由于不明原因,必须使用float而不能用double float InvSqrt(float m) { float mhalf = 0.5f * m; int i = *(int*) &m; i = 0x5f375a86 - (i >> 1); // 这个常数是多次测试后找到的最精确的 m = *(float*) &i; m = m * (1.5f - mhalf * m * m); // 迭代次数取决于所要求的精度 // m = m * (1.5f - mhalf * m * m);// m = m * (1.5f - mhalf * m * m); return 1/m; float mhalf = 0.5f * m; int i = *(int*) &m; i = 0x5f375a86 - (i >> 1); // 这个常数是多次测试后找到的最精确的 m = *(float*) &i; m = m * (1.5f - mhalf * m * m); // 迭代次数取决于所要求的精度 // m = m * (1.5f - mhalf * m * m);// m = m * (1.5f - mhalf * m * m); return 1/m;}
// 约翰-卡马克(John Carmack)double Q_rsqrt(double number) {9 行未改动 return 1 / y;}```## 线性基```cpp```cpp line-numbersstruct LinearBase { int dat[N]; void insert(int x) { for (int i = 63;~i;i--) {7 行未改动 }} lb;```## 日期计算```cpp```cpp line-numbersstruct _time { int y, m, d, h, min, s; int mmod[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int y, m, d, h, min, s; int mmod[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
_time() : y(0), m(0), d(0), h(0), min(0), s(0) {} _time() : y(0), m(0), d(0), h(0), min(0), s(0) {}
_time(int year, int month, int day, int hour, int minute, int second) : y(year), m(month), d(day), h(hour), min(minute), s(second) { adjust_for_leap_year(); } _time(int year, int month, int day, int hour, int minute, int second) : y(year), m(month), d(day), h(hour), min(minute), s(second) { adjust_for_leap_year(); }
bool is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } bool is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }
void adjust_for_leap_year() { void adjust_for_leap_year() { if (is_leap_year(y)) mmod[2] = 29; else mmod[2] = 28; } }
friend _time operator + (const _time &a, const _time &b) { _time c; c.s = a.s + b.s; c.min = a.min + b.min + c.s / 60; c.s %= 60; c.h = a.h + b.h + c.min / 60; c.min %= 60; c.d = a.d + b.d + c.h / 24; c.h %= 24; c.m = a.m + b.m; c.y = a.y + b.y; friend _time operator + (const _time &a, const _time &b) { _time c; c.s = a.s + b.s; c.min = a.min + b.min + c.s / 60; c.s %= 60; c.h = a.h + b.h + c.min / 60; c.min %= 60; c.d = a.d + b.d + c.h / 24; c.h %= 24; c.m = a.m + b.m; c.y = a.y + b.y;
c.adjust_for_leap_year(); c.adjust_for_leap_year();
while (c.d > c.mmod[c.m]) { c.d -= c.mmod[c.m]; c.m++; if (c.m > 12) { c.m = 1; c.y++; c.adjust_for_leap_year(); } } while (c.d > c.mmod[c.m]) { c.d -= c.mmod[c.m]; c.m++; if (c.m > 12) { c.m = 1; c.y++; c.adjust_for_leap_year(); } }
return c; } return c; }
friend _time operator - (const _time &a, const _time &b) { _time c; c.s = a.s - b.s; c.min = a.min - b.min; c.h = a.h - b.h; c.d = a.d - b.d; c.m = a.m - b.m; c.y = a.y - b.y; friend _time operator - (const _time &a, const _time &b) { _time c; c.s = a.s - b.s; c.min = a.min - b.min; c.h = a.h - b.h; c.d = a.d - b.d; c.m = a.m - b.m; c.y = a.y - b.y;
if (c.s < 0) { c.s += 60; c.min--; } if (c.min < 0) { c.min += 60; c.h--; } if (c.h < 0) { c.h += 24; c.d--; } while (c.d <= 0) { c.m--; if (c.m <= 0) { c.m = 12; c.y--; } c.adjust_for_leap_year(); c.d += c.mmod[c.m]; } if (c.s < 0) { c.s += 60; c.min--; } if (c.min < 0) { c.min += 60; c.h--; } if (c.h < 0) { c.h += 24; c.d--; } while (c.d <= 0) { c.m--; if (c.m <= 0) { c.m = 12; c.y--; } c.adjust_for_leap_year(); c.d += c.mmod[c.m]; }
return c; } return c; }
friend istream& operator >> (istream &in, _time &t) { in >> t.y >> t.m >> t.d >> t.h >> t.min >> t.s; return in; } friend istream& operator >> (istream &in, _time &t) { in >> t.y >> t.m >> t.d >> t.h >> t.min >> t.s; return in; }
friend ostream& operator << (ostream &out, const _time &t) { out << t.y << "-" << setw(2) << setfill('0') << t.m << "-" << setw(2) << setfill('0') << t.d << " " << setw(2) << setfill('0') << t.h << ":" << setw(2) << setfill('0') << t.min << ":" << setw(2) << setfill('0') << t.s; return out; } friend ostream& operator << (ostream &out, const _time &t) { out << t.y << "-" << setw(2) << setfill('0') << t.m << "-" << setw(2) << setfill('0') << t.d << " " << setw(2) << setfill('0') << t.h << ":" << setw(2) << setfill('0') << t.min << ":" << setw(2) << setfill('0') << t.s; return out; }};```## Base 64 编码 / 解码```cpp```cpp line-numbers#include <bits/stdc++.h>using namespace std;
static const string base64_chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ""abcdefghijklmnopqrstuvwxyz""0123456789+/";
string base64_encode(char const* buf, int bufLen) { string ret; int i = 0; int j = 0; char char_array_3[3]; char char_array_4[4]; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0;i < 4;i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0;j < i + 1;j++) ret += base64_chars[char_array_4[j]]; while (i++ < 3) ret += '='; } return ret; string ret; int i = 0; int j = 0; char char_array_3[3]; char char_array_4[4]; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0;i < 4;i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0;j < i + 1;j++) ret += base64_chars[char_array_4[j]]; while (i++ < 3) ret += '='; } return ret;}
string base64_decode(string encoded_string) { vector <char> ret; int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; char char_array_4[4], char_array_3[3]; while (in_len-- && ( encoded_string[in_] != '=') && isalnum(encoded_string[in_]) || (encoded_string[in_] == '+') || (encoded_string[in_] == '/')) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0;i < 4;i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0;i < 3;i++) ret.push_back(char_array_3[i]); i = 0; } } if (i) { for (j = i;j < 4;j++) char_array_4[j] = 0; for (j = 0;j < 4;j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0;j < i - 1;j++) ret.push_back(char_array_3[j]); } string ans; for (char i : ret) ans += i; vector <char> ret; int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; char char_array_4[4], char_array_3[3]; while (in_len-- && ( encoded_string[in_] != '=') && isalnum(encoded_string[in_]) || (encoded_string[in_] == '+') || (encoded_string[in_] == '/')) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0;i < 4;i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0;i < 3;i++) ret.push_back(char_array_3[i]); i = 0; } } if (i) { for (j = i;j < 4;j++) char_array_4[j] = 0; for (j = 0;j < 4;j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0;j < i - 1;j++) ret.push_back(char_array_3[j]); } string ans; for (char i : ret) ans += i;
return ans; return ans;}
signed main() { string s; char c[1000002]; cin >> s; for (int i = 0;i < s.size();i++) c[i] = s[i]; cout << base64_encode(c, 64) << endl << base64_decode(s) << endl; return 0; string s; char c[1000002]; cin >> s; for (int i = 0;i < s.size();i++) c[i] = s[i]; cout << base64_encode(c, 64) << endl << base64_decode(s) << endl; return 0;}```## 欧拉(线性)筛质数```cpp## 欧拉(线性)质数筛```cpp line-numbersint pr[N];bool ip[N];
int gp(int n) { int p = 0; memset(ip, 1, sizeof(ip)); ip[1] = 0; for (int i = 2;i <= n;i++) { if (ip[i]) pr[++p] = i; for (int j = 1;j <= p && i * pr[j] <= n;j++) { ip[i * pr[j]] = 0; if (i % pr[j] == 0) break; } } int p = 0; memset(ip, 1, sizeof(ip)); ip[1] = 0; for (int i = 2;i <= n;i++) { if (ip[i]) pr[++p] = i; for (int j = 1;j <= p && i * pr[j] <= n;j++) { ip[i * pr[j]] = 0; if (i % pr[j] == 0) break; } } return p;}```## 归并排序```cpp```cpp line-numbersint a[N], b[N], c[N], ans1, ans2, n, _;
void msort(int l, int r, int &ans, auto &A, auto &B) { if (l == r) return; int mid = (l + r) / 2; msort(l, mid, ans, A, B); msort(mid + 1, r, ans, A, B); int i = l, j = mid + 1, p = l; while (i <= mid && j <= r) { if (A[i] <= A[j]) B[p++] = A[i++]; else B[p++] = A[j++], ans += mid - i + 1; } while (i <= mid) B[p++] = A[i++]; while (j <= r) B[p++] = A[j++]; for (int k = l;k <= r;k++) A[k] = B[k]; if (l == r) return; int mid = (l + r) / 2; msort(l, mid, ans, A, B); msort(mid + 1, r, ans, A, B); int i = l, j = mid + 1, p = l; while (i <= mid && j <= r) { if (A[i] <= A[j]) B[p++] = A[i++]; else B[p++] = A[j++], ans += mid - i + 1; } while (i <= mid) B[p++] = A[i++]; while (j <= r) B[p++] = A[j++]; for (int k = l;k <= r;k++) A[k] = B[k];}```## 矩阵快速幂 / 矩阵乘法```cpp```cpp line-numbers#include <bits/stdc++.h>using namespace std;
const ll N = 1e2 + 2, mod = 1e9 + 7;35 行未改动 } return 0;}```## 高精度from oi-wiki```cppstruct bign { int d[N], len; void clean() { while (len > 1 && !d[len-1]) len--; } bign() { memset(d, 0, sizeof(d)); len = 1; } bign(int num) { *this = num; } bign(char* num) { *this = num; } bign operator = (const char* num) { memset(d, 0, sizeof(d)); len = strlen(num); for (int i = 0;i < len;i++) d[i] = num[len - 1 - i] - '0'; clean(); return *this; } bign operator = (int num) { char s[20]; sprintf(s, "%d", num); *this = s; return *this; } bign operator + (const bign& b) { bign c = *this; int i; for (i = 0;i < b.len;i++) { c.d[i] += b.d[i]; if (c.d[i] > 9) c.d[i] %= 10, c.d[i+1]++; } while (c.d[i] > 9) c.d[i++] %= 10, c.d[i]++; c.len = max(len, b.len); if (c.d[i] && c.len <= i) c.len = i + 1; return c; } bign operator - (const bign& b) { bign c = *this; int i; for (i = 0;i < b.len;i++) { c.d[i] -= b.d[i]; if (c.d[i] < 0) c.d[i] += 10, c.d[i + 1]--; } while (c.d[i] < 0) c.d[i++] += 10, c.d[i]--; c.clean(); return c; } bign operator * (const bign& b) const { int i, j; bign c; c.len = len + b.len; for (j = 0;j < b.len;j++) for(i = 0;i < len;i++) c.d[i + j] += d[i] * b.d[j]; for (i = 0;i < c.len - 1;i++) c.d[i + 1] += c.d[i] / 10, c.d[i] %= 10; c.clean(); return c; } bign operator / (const bign& b) { int i, j; bign c = *this, a = 0; for (i = len - 1;i >= 0;i--) { a = a * 10 + d[i]; for (j = 0;j < 10;j++) if (a < b * (j + 1)) break; c.d[i] = j; a = a - b * j; } c.clean(); return c; } bign operator % (const bign& b) { int i, j; bign a = 0; for (i = len - 1;i >= 0;i--) { a = a * 10 + d[i]; for (j = 0;j < 10;j++) if (a < b * (j + 1)) break; a = a - b * j; } return a; } bign operator += (const bign& b) { *this = *this + b; return *this; }
bool operator < (const bign& b) const { if (len != b.len) return len < b.len; for (int i = len - 1;i >= 0;i--) if (d[i] != b.d[i]) return d[i] < b.d[i]; return false; } bool operator > (const bign& b) const { return b < *this; } bool operator <= (const bign& b) const { return !(b < *this); } bool operator >= (const bign& b) const { return !(*this < b); } bool operator != (const bign& b) const { return b < *this || *this < b; } bool operator == (const bign& b) const { return !(b < *this) && !(b > *this); }
string str() const { char s[maxn]= {}; for (int i = 0;i < len;i++) s[len - 1 - i] = d[i] + '0'; return s; }};istream& operator >> (istream& in, bign& x) { string s; in >> s; x = s.c_str(); return in;}ostream& operator << (ostream& out, const bign& x) { out << x.str(); return out;}```## 快速位运算```cpp```cpp line-numbersint getor(int l, int r) { if (l == r) return l; return l | ((1 << ( __lg(l ^ r) + 1)) - 1);}10 行未改动 if (x % 4 == 2) return x + 1; if (x % 4 == 3) return 0;}```## ext_double(高精度浮点数,未格式化)```cpp#include <iostream>#include <vector>#include <string>#include <algorithm>#include <cmath>#include <complex>#include <stdexcept>#include <cctype>#include <limits>#include <type_traits>
using namespace std;
const double PI = acos(-1);
// FFT 辅助函数void fft(vector<complex<double>>& a, bool invert) { int n = a.size(); if (n == 1) return;
vector<complex<double>> a0(n / 2), a1(n / 2); for (int i = 0, j = 0; i < n; i += 2, j++) { a0[j] = a[i]; a1[j] = a[i + 1]; } fft(a0, invert); fft(a1, invert);
double ang = 2 * PI / n * (invert ? -1 : 1); complex<double> w(1), wn(cos(ang), sin(ang)); for (int i = 0; i < n / 2; i++) { a[i] = a0[i] + w * a1[i]; a[i + n / 2] = a0[i] - w * a1[i]; if (invert) { a[i] /= 2; a[i + n / 2] /= 2; } w *= wn; }}
// 使用FFT进行大整数乘法vector<int> multiply_bigint(const vector<int>& a, const vector<int>& b) { vector<complex<double>> fa(a.begin(), a.end()), fb(b.begin(), b.end()); size_t n = 1; size_t max_size = max(a.size(), b.size()); while (n < max_size) n <<= 1; n <<= 1; fa.resize(n); fb.resize(n);
fft(fa, false); fft(fb, false); for (size_t i = 0; i < n; i++) { fa[i] *= fb[i]; } fft(fa, true);
vector<int> result(n); int carry = 0; for (size_t i = 0; i < n; i++) { int temp = int(fa[i].real() + 0.5) + carry; carry = temp / 10; result[i] = temp % 10; }
// 移除前导零 while (result.size() > 1 && result.back() == 0) { result.pop_back(); } return result;}
class ext_double {private: vector<int> digits; // 数字位(0-9),按小端序存储 int exponent; // 指数(10的幂) bool sign; // 符号(true为负) static const int PRECISION = 100; // 默认精度(位数)
// 规范化数字(移除前导/后缀零,调整指数) void normalize() { // 移除前导零 size_t leading_zeros = 0; while (leading_zeros < digits.size() && digits[leading_zeros] == 0) { leading_zeros++; } if (leading_zeros > 0) { digits.erase(digits.begin(), digits.begin() + leading_zeros); if (digits.empty()) { digits.push_back(0); exponent = 0; sign = false; return; } }
// 移除后缀零 size_t trailing_zeros = 0; while (trailing_zeros < digits.size() && digits[digits.size() - 1 - trailing_zeros] == 0) { trailing_zeros++; } if (trailing_zeros > 0) { digits.erase(digits.end() - trailing_zeros, digits.end()); exponent += trailing_zeros; if (digits.empty()) { digits.push_back(0); exponent = 0; sign = false; return; } }
// 处理零值情况 if (digits.size() == 1 && digits[0] == 0) { exponent = 0; sign = false; } }
// 绝对值加法辅助函数 static ext_double add_absolute(const ext_double& a, const ext_double& b) { ext_double result; int exp_diff = a.exponent - b.exponent; const ext_double* larger = (exp_diff >= 0) ? &a : &b; const ext_double* smaller = (exp_diff >= 0) ? &b : &a; exp_diff = abs(exp_diff); result.exponent = larger->exponent; result.digits = larger->digits; // 限制填充的零的数量,防止过大 size_t max_padding = 1000; // 设置一个合理的最大值 size_t padding = min(static_cast<size_t>(exp_diff), max_padding); if (padding > 0) { result.digits.insert(result.digits.end(), padding, 0); result.exponent -= padding; } // 数字相加 int carry = 0; size_t i = 0; for (; i < smaller->digits.size() && i < result.digits.size(); i++) { int sum = result.digits[i] + smaller->digits[i] + carry; carry = sum / 10; result.digits[i] = sum % 10; } // 处理剩余位数 for (; i < smaller->digits.size(); i++) { int sum = smaller->digits[i] + carry; carry = sum / 10; result.digits.push_back(sum % 10); } // 处理进位 while (carry > 0) { if (i < result.digits.size()) { int sum = result.digits[i] + carry; carry = sum / 10; result.digits[i] = sum % 10; i++; } else { result.digits.push_back(carry % 10); carry /= 10; } } return result; }
// 绝对值减法辅助函数(a必须>=b) static ext_double subtract_absolute(const ext_double& a, const ext_double& b) { ext_double result; int exp_diff = a.exponent - b.exponent; result.exponent = a.exponent; result.digits = a.digits;
// 必要时填充零 if (exp_diff > 0) { result.digits.insert(result.digits.end(), exp_diff, 0); result.exponent -= exp_diff; }
// 数字相减 int borrow = 0; for (size_t i = 0; i < b.digits.size(); i++) { int diff = result.digits[i] - b.digits[i] - borrow; if (diff < 0) { diff += 10; borrow = 1; } else { borrow = 0; } result.digits[i] = diff; }
// 处理借位 size_t i = b.digits.size(); while (borrow > 0 && i < result.digits.size()) { if (result.digits[i] > 0) { result.digits[i]--; borrow = 0; } else { result.digits[i] = 9; i++; } }
// 移除前导零并规范化 result.normalize(); return result; }
// 比较绝对值(忽略符号) static int compare_absolute(const ext_double& a, const ext_double& b) { int a_exp = a.exponent + a.digits.size(); int b_exp = b.exponent + b.digits.size();
if (a_exp != b_exp) { return (a_exp > b_exp) ? 1 : -1; }
// 逐位比较 size_t max_len = max(a.digits.size(), b.digits.size()); for (size_t i = 0; i < max_len; i++) { int a_digit = (i < a.digits.size()) ? a.digits[i] : 0; int b_digit = (i < b.digits.size()) ? b.digits[i] : 0; if (a_digit != b_digit) { return (a_digit > b_digit) ? 1 : -1; } } return 0; }
public: // 构造函数 ext_double() : digits({0}), exponent(0), sign(false) {}## 快速傅里叶变换(FFT / IFFT)```cpp line-numbersstruct Complex { double x, y; ext_double(const string& s) { from_string(s); } ext_double(const char* s) { from_string(string(s)); } // 基本类型构造函数 ext_double(int i) { from_string(std::to_string(i)); } ext_double(long l) { from_string(std::to_string(l)); } ext_double(long long ll) { from_string(std::to_string(ll)); } ext_double(unsigned u) { from_string(std::to_string(u)); } ext_double(unsigned long ul) { from_string(std::to_string(ul)); } ext_double(unsigned long long ull) { from_string(std::to_string(ull)); } ext_double(short s) { from_string(std::to_string(s)); } ext_double(float f) { from_string(std::to_string(f)); } ext_double(double d) { from_string(std::to_string(d)); } ext_double(long double ld) { from_string(std::to_string(ld)); }
// 特殊值 static ext_double infinity() { ext_double result; result.digits = {9,9,9}; // 表示无穷大的特殊值 result.exponent = numeric_limits<int>::max(); return result; Complex(double _x = 0.0, double _y = 0.0) { x = _x; y = _y; }
static ext_double quiet_NaN() { ext_double result; result.digits = {1,2,3}; // 表示NaN的特殊值 result.exponent = numeric_limits<int>::max()-1; return result; }
// 从字符串解析 void from_string(string s) { digits.clear(); exponent = 0; sign = false;
// 处理特殊值 if (s == "inf" || s == "INF" || s == "Infinity") { *this = infinity(); return; } if (s == "nan" || s == "NaN" || s == "NAN") { *this = quiet_NaN(); return; }
// 处理符号 if (!s.empty() && s[0] == '-') { sign = true; s = s.substr(1); }
// 清理非数字字符(保留.和e/E) string cleaned; bool has_decimal = false; int decimal_pos = 0; bool has_exponent = false; int exponent_pos = 0; int exponent_sign = 1; string exponent_str;
for (size_t i = 0; i < s.size(); i++) { if (isdigit(s[i])) { cleaned += s[i]; } else if (s[i] == '.' && !has_decimal && !has_exponent) { has_decimal = true; decimal_pos = cleaned.size(); } else if ((s[i] == 'e' || s[i] == 'E') && !has_exponent) { has_exponent = true; exponent_pos = i; } }
// 解析指数部分 if (has_exponent) { string remaining = s.substr(exponent_pos + 1); if (!remaining.empty() && remaining[0] == '+') { remaining = remaining.substr(1); } else if (!remaining.empty() && remaining[0] == '-') { exponent_sign = -1; remaining = remaining.substr(1); } for (char c : remaining) { if (isdigit(c)) { exponent_str += c; } } if (!exponent_str.empty()) { exponent = stoi(exponent_str) * exponent_sign; } }
// 处理清理后的字符串 if (cleaned.empty()) { digits = {0}; exponent = 0; sign = false; return; }
// 移除前导零 size_t leading_zeros = 0; while (leading_zeros < cleaned.size() && cleaned[leading_zeros] == '0') { leading_zeros++; } if (leading_zeros > 0) { cleaned = cleaned.substr(leading_zeros); }
// 处理零值情况 if (cleaned.empty()) { digits = {0}; exponent = 0; sign = false; return; }
// 以逆序存储数字(最低位在前) for (int i = cleaned.size() - 1; i >= 0; i--) { digits.push_back(cleaned[i] - '0'); }
// 根据小数点位置调整指数 if (has_decimal) { exponent += (decimal_pos - (int)cleaned.size()); }
// 规范化数字 normalize(); }
// 转换为字符串 string to_string() const { // 处理特殊值 if (digits.size() == 3 && exponent == numeric_limits<int>::max()) { if (digits[0] == 9 && digits[1] == 9 && digits[2] == 9) { return sign ? "-inf" : "inf"; } return "nan"; }
string result; if (sign) result += '-';
if (exponent >= 0) { // 数字 >= 1 for (int i = digits.size() - 1; i >= 0; i--) { result += char(digits[i] + '0'); } result += string(exponent, '0'); } else if (static_cast<size_t>(-exponent) < digits.size()) { // 数字在0和1之间但小数点前有非零位 int decimal_pos = digits.size() + exponent; for (int i = digits.size() - 1; i >= decimal_pos; i--) { result += char(digits[i] + '0'); } if (decimal_pos > 0) { result += '.'; for (int i = decimal_pos - 1; i >= 0; i--) { result += char(digits[i] + '0'); } } } else { // 数字 < 0.1 result += "0."; result += string(-exponent - digits.size(), '0'); for (int i = digits.size() - 1; i >= 0; i--) { result += char(digits[i] + '0'); } }
return result; }
// 转换为基本类型 explicit operator int() const { return stoi(to_string()); } explicit operator long() const { return stol(to_string()); } explicit operator long long() const { return stoll(to_string()); } explicit operator unsigned() const { return stoul(to_string()); } explicit operator unsigned long() const { return stoul(to_string()); } explicit operator unsigned long long() const { return stoull(to_string()); } explicit operator float() const { return stof(to_string()); } explicit operator double() const { return stod(to_string()); } explicit operator long double() const { return stold(to_string()); } explicit operator bool() const { return *this != ext_double(0); }
// 算术运算符 ext_double operator+(const ext_double& other) const { if (sign == other.sign) { ext_double result = add_absolute(*this, other); result.sign = sign; return result; } else { int cmp = compare_absolute(*this, other); if (cmp == 0) { return ext_double(); } else if (cmp > 0) { ext_double result = subtract_absolute(*this, other); result.sign = sign; return result; } else { ext_double result = subtract_absolute(other, *this); result.sign = other.sign; return result; } } }
ext_double operator-(const ext_double& other) const { if (sign != other.sign) { ext_double result = add_absolute(*this, other); result.sign = sign; return result; } else { int cmp = compare_absolute(*this, other); if (cmp == 0) { return ext_double(); } else if (cmp > 0) { ext_double result = subtract_absolute(*this, other); result.sign = sign; return result; } else { ext_double result = subtract_absolute(other, *this); result.sign = !other.sign; return result; } } }
ext_double operator*(const ext_double& other) const { ext_double result; result.sign = sign != other.sign; result.exponent = exponent + other.exponent;
// 使用FFT进行乘法 result.digits = multiply_bigint(digits, other.digits); result.exponent += digits.size() + other.digits.size() - result.digits.size(); result.normalize(); return result; }
ext_double operator/(const ext_double& other) const { if (other.digits.size() == 1 && other.digits[0] == 0) { return sign ? -infinity() : infinity(); }
ext_double result; result.sign = sign != other.sign; result.exponent = exponent - other.exponent;
// 复制被除数和除数 vector<int> dividend = digits; vector<int> divisor = other.digits;
// 规范化除数到 >= 0.1 且 < 1.0 int divisor_shift = divisor.size(); divisor.insert(divisor.end(), PRECISION * 2, 0); result.exponent -= divisor_shift;
// 执行长除法 result.digits.clear(); vector<int> current;
for (size_t i = 0; i < dividend.size() + PRECISION * 2; i++) { int digit = (i < dividend.size()) ? dividend[dividend.size() - 1 - i] : 0; current.insert(current.begin(), digit);
// 移除前导零 while (!current.empty() && current.back() == 0) { current.pop_back(); } if (current.empty()) { result.digits.push_back(0); continue; }
// 比较current和divisor int cmp = 0; if (current.size() != divisor.size()) { cmp = current.size() > divisor.size() ? 1 : -1; } else { for (int j = current.size() - 1; j >= 0; j--) { if (current[j] != divisor[j]) { cmp = current[j] > divisor[j] ? 1 : -1; break; } } }
if (cmp < 0) { result.digits.push_back(0); continue; }
// 执行减法 int quotient = 0; while (cmp >= 0) { quotient++; int borrow = 0; for (size_t j = 0; j < divisor.size(); j++) { int diff = current[j] - divisor[j] - borrow; if (diff < 0) { diff += 10; borrow = 1; } else { borrow = 0; } current[j] = diff; }
// 移除前导零 while (!current.empty() && current.back() == 0) { current.pop_back(); }
// 重新比较 if (current.size() != divisor.size()) { cmp = current.size() > divisor.size() ? 1 : -1; } else { cmp = 0; for (int j = current.size() - 1; j >= 0; j--) { if (current[j] != divisor[j]) { cmp = current[j] > divisor[j] ? 1 : -1; break; } } } }
result.digits.push_back(quotient); }
// 反转数字以获得正确顺序 reverse(result.digits.begin(), result.digits.end()); result.normalize(); return result; }
ext_double operator%(const ext_double& other) const { ext_double quotient = *this / other; ext_double truncated = floor(quotient); return *this - truncated * other; }
// 复合赋值运算符 ext_double& operator+=(const ext_double& other) { *this = *this + other; return *this; } ext_double& operator-=(const ext_double& other) { *this = *this - other; return *this; } ext_double& operator*=(const ext_double& other) { *this = *this * other; return *this; } ext_double& operator/=(const ext_double& other) { *this = *this / other; return *this; } ext_double& operator%=(const ext_double& other) { *this = *this % other; return *this; }
// 自增自减运算符 ext_double& operator++() { *this += ext_double(1); return *this; } // 前置++ ext_double operator++(int) { ext_double tmp = *this; ++*this; return tmp; } // 后置++ ext_double& operator--() { *this -= ext_double(1); return *this; } // 前置-- ext_double operator--(int) { ext_double tmp = *this; --*this; return tmp; } // 后置--
// 比较运算符 bool operator==(const ext_double& other) const { if (sign != other.sign) return false; if (exponent != other.exponent) return false; if (digits.size() != other.digits.size()) return false; for (size_t i = 0; i < digits.size(); i++) { if (digits[i] != other.digits[i]) return false; } return true; }
bool operator!=(const ext_double& other) const { return !(*this == other); }
bool operator<(const ext_double& other) const { if (sign != other.sign) return sign; if (sign) { return compare_absolute(*this, other) > 0; } else { return compare_absolute(*this, other) < 0; } }
bool operator>(const ext_double& other) const { if (sign != other.sign) return !sign; if (sign) { return compare_absolute(*this, other) < 0; } else { return compare_absolute(*this, other) > 0; } }
bool operator<=(const ext_double& other) const { return !(*this > other); } bool operator>=(const ext_double& other) const { return !(*this < other); }
// 一元运算符 ext_double operator-() const { ext_double result = *this; result.sign = !sign; return result; }
ext_double operator+() const { return *this; }
// 赋值运算符 ext_double& operator=(const ext_double& other) = default; // 基本类型赋值运算符 ext_double& operator=(int i) { return *this = ext_double(i); } ext_double& operator=(long l) { return *this = ext_double(l); } ext_double& operator=(long long ll) { return *this = ext_double(ll); } ext_double& operator=(unsigned u) { return *this = ext_double(u); } ext_double& operator=(unsigned long ul) { return *this = ext_double(ul); } ext_double& operator=(unsigned long long ull) { return *this = ext_double(ull); } ext_double& operator=(short s) { return *this = ext_double(s); } ext_double& operator=(float f) { return *this = ext_double(f); } ext_double& operator=(double d) { return *this = ext_double(d); } ext_double& operator=(long double ld) { return *this = ext_double(ld); }
// 与基本类型的算术运算 friend ext_double operator+(const ext_double& a, int b) { return a + ext_double(b); } friend ext_double operator+(int a, const ext_double& b) { return ext_double(a) + b; } friend ext_double operator-(const ext_double& a, int b) { return a - ext_double(b); } friend ext_double operator-(int a, const ext_double& b) { return ext_double(a) - b; } friend ext_double operator*(const ext_double& a, int b) { return a * ext_double(b); } friend ext_double operator*(int a, const ext_double& b) { return ext_double(a) * b; } friend ext_double operator/(const ext_double& a, int b) { return a / ext_double(b); } friend ext_double operator/(int a, const ext_double& b) { return ext_double(a) / b; } friend ext_double operator%(const ext_double& a, int b) { return a % ext_double(b); } friend ext_double operator%(int a, const ext_double& b) { return ext_double(a) % b; }
// 其他基本类型的类似定义... template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator+(const ext_double& a, T b) { return a + ext_double(b); } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator+(T a, const ext_double& b) { return ext_double(a) + b; } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator-(const ext_double& a, T b) { return a - ext_double(b); } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator-(T a, const ext_double& b) { return ext_double(a) - b; } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator*(const ext_double& a, T b) { return a * ext_double(b); } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator*(T a, const ext_double& b) { return ext_double(a) * b; } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator/(const ext_double& a, T b) { return a / ext_double(b); } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator/(T a, const ext_double& b) { return ext_double(a) / b; } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator%(const ext_double& a, T b) { return a % ext_double(b); } template<typename T, typename = enable_if_t<is_arithmetic_v<T>>> friend ext_double operator%(T a, const ext_double& b) { return ext_double(a) % b; }
// 流操作符 friend ostream& operator<<(ostream& os, const ext_double& num) { os << num.to_string(); return os; Complex operator - (const Complex &b) const { return Complex(x - b.x, y - b.y); }
friend istream& operator>>(istream& is, ext_double& num) { string s; is >> s; num.from_string(s); return is; }
// 数学函数声明为友元 friend ext_double sqrt(const ext_double& x); friend ext_double cbrt(const ext_double& x); friend ext_double pow(const ext_double& base, const ext_double& exponent); friend ext_double abs(const ext_double& x); friend ext_double floor(const ext_double& x); friend ext_double ceil(const ext_double& x); friend ext_double round(const ext_double& x); friend ext_double fmod(const ext_double& x, const ext_double& y); friend ext_double fabs(const ext_double& x); friend bool isnan(const ext_double& x); friend bool isinf(const ext_double& x); friend bool isfinite(const ext_double& x);};
// 数学函数实现ext_double sqrt(const ext_double& x) { if (isnan(x)) return x; if (x < ext_double(0)) return ext_double::quiet_NaN(); if (x == ext_double(0) || x == ext_double(1)) return x; if (isinf(x)) return x;
ext_double precision = ext_double("0.0000000000000001"); ext_double last; ext_double start = ext_double(0); ext_double end = x; if (x < ext_double(1)) { end = ext_double(1); Complex operator + (const Complex &b) const { return Complex(x + b.x, y + b.y); }
ext_double mid = (start + end) / ext_double(2); do { if (mid * mid > x) { end = mid; } else { start = mid; } last = mid; mid = (start + end) / ext_double(2); } while (abs(last - mid) > precision); return last;}
ext_double cbrt(const ext_double& x) { if (isnan(x)) return x; if (isinf(x)) return x;
ext_double precision = ext_double("0.0000000000000001"); ext_double last; ext_double start, end; if (x >= ext_double(0)) { start = ext_double(0); end = x; if (x < ext_double(1)) { end = ext_double(1); } } else { start = x; end = ext_double(0); if (x > ext_double(-1)) { start = ext_double(-1); } Complex operator * (const Complex &b) const { return Complex(x * b.x - y * b.y, x * b.y + y * b.x); }
ext_double mid = (start + end) / ext_double(2); do { ext_double cube = mid * mid * mid; if (cube > x) { end = mid; } else { start = mid; } last = mid; mid = (start + end) / ext_double(2); } while (abs(last - mid) > precision); return last;}
ext_double pow(const ext_double& base, const ext_double& exponent) { if (isnan(base) || isnan(exponent)) return ext_double::quiet_NaN(); if (exponent == ext_double(0)) return ext_double(1); if (base == ext_double(0)) { if (exponent > ext_double(0)) return ext_double(0); else return ext_double::infinity(); } if (isinf(exponent)) { if (abs(base) > ext_double(1)) { return exponent > ext_double(0) ? ext_double::infinity() : ext_double(0); } else if (abs(base) == ext_double(1)) { return ext_double(1); } else { return exponent > ext_double(0) ? ext_double(0) : ext_double::infinity(); } }
// 检查指数是否为整数 if (exponent.exponent >= 0 && exponent.digits.size() == 1) { // 快速幂算法实现 int n = exponent.digits[0]; bool negative = false; if (n < 0) { negative = true; n = -n; }
ext_double result(1); ext_double x = base; while (n > 0) { if (n % 2 == 1) { result = result * x; } x = x * x; n = n / 2; }
if (negative) { return ext_double(1) / result; } else { return result; } } // 对于非整数指数,使用exp(y*ln(x))实现 // 这里需要实现ln和exp函数,暂用简单方法 return ext_double(std::pow((double)base, (double)exponent));}
ext_double abs(const ext_double& x) { ext_double result = x; result.sign = false; return result;}
ext_double floor(const ext_double& x) { if (isnan(x) || isinf(x)) return x; string s = x.to_string(); size_t dot_pos = s.find('.'); if (dot_pos == string::npos) return x; return ext_double(s.substr(0, dot_pos));}
ext_double ceil(const ext_double& x) { if (isnan(x) || isinf(x)) return x; ext_double floored = floor(x); if (floored == x) return x; return floored + ext_double(1);}
ext_double round(const ext_double& x) { if (isnan(x) || isinf(x)) return x; ext_double floored = floor(x); ext_double decimal = x - floored; if (decimal >= ext_double("0.5")) { return floored + ext_double(1); } else { return floored; }}
ext_double fmod(const ext_double& x, const ext_double& y) { if (isnan(x) || isnan(y) || isinf(x) || y == ext_double(0)) { return ext_double::quiet_NaN(); } if (isinf(y)) return x; return x % y;}
ext_double fabs(const ext_double& x) { return abs(x); }
bool isnan(const ext_double& x) { return x.digits.size() == 3 && x.exponent == numeric_limits<int>::max()-1 && x.digits[0] == 1 && x.digits[1] == 2 && x.digits[2] == 3;}
bool isinf(const ext_double& x) { return x.digits.size() == 3 && x.exponent == numeric_limits<int>::max() && x.digits[0] == 9 && x.digits[1] == 9 && x.digits[2] == 9;}
bool isfinite(const ext_double& x) { return !isnan(x) && !isinf(x);}
// 类型特征namespace std { template<> class numeric_limits<ext_double> { public: static constexpr bool is_specialized = true; static constexpr bool is_signed = true; static constexpr bool is_integer = false; static constexpr bool is_exact = false; static constexpr bool has_infinity = true; static constexpr bool has_quiet_NaN = true; static constexpr bool has_signaling_NaN = false; static constexpr float_denorm_style has_denorm = denorm_absent; static constexpr bool has_denorm_loss = false; static constexpr float_round_style round_style = round_to_nearest; static constexpr bool is_iec559 = false; static constexpr bool is_bounded = false; static constexpr bool is_modulo = false; static constexpr int digits = 1000; // 大约1000位十进制精度 static constexpr int digits10 = 1000; static constexpr int max_digits10 = 0; static constexpr int radix = 10; static constexpr int min_exponent = -1000000; static constexpr int min_exponent10 = -1000000; static constexpr int max_exponent = 1000000; static constexpr int max_exponent10 = 1000000; static constexpr bool traps = false; static constexpr bool tinyness_before = false;
static ext_double min() { return ext_double("1e-1000000"); } static ext_double max() { return ext_double("1e+1000000"); } static ext_double lowest() { return -max(); } static ext_double epsilon() { return ext_double("1e-100"); } static ext_double round_error() { return ext_double("0.5"); } static ext_double infinity() { return ext_double::infinity(); } static ext_double quiet_NaN() { return ext_double::quiet_NaN(); } static ext_double signaling_NaN() { return ext_double::quiet_NaN(); } static ext_double denorm_min() { return min(); } };}
// 示例用法int main() { ext_double a = 123.456; ext_double b = "789.01234567890123456789"; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a + b = " << a + b << endl; cout << "a - b = " << a - b << endl; cout << "a * b = " << a * b << endl; cout << "a / b = " << a / b << endl; cout << "a % b = " << a % b << endl; a += b; cout << "a += b -> a = " << a << endl; cout << "sqrt(2) = " << sqrt(ext_double(2)) << endl; cout << "cbrt(27) = " << cbrt(ext_double(27)) << endl; cout << "pow(2, 10) = " << pow(ext_double(2), ext_double(10)) << endl; cout << "floor(3.7) = " << floor(ext_double("3.7")) << endl; cout << "ceil(3.2) = " << ceil(ext_double("3.2")) << endl; cout << "round(3.5) = " << round(ext_double("3.5")) << endl; cout << "infinity: " << ext_double::infinity() << endl; cout << "NaN: " << ext_double::quiet_NaN() << endl; return 0;}```## 快速傅里叶变换 / 逆变换(FFT / IFFT)```cppstruct Complex { double x, y; Complex(double _x = 0.0, double _y = 0.0) { x = _x; y = _y; } Complex operator - (const Complex &b) const { return Complex(x - b.x, y - b.y); } Complex operator + (const Complex &b) const { return Complex(x + b.x, y + b.y); } Complex operator * (const Complex &b) const { return Complex(x * b.x - y * b.y, x * b.y + y * b.x); }};
int rev[N];
// 同样需要保证 len 是 2 的幂// 记 rev[i] 为 i 翻转后的值void change(Complex y[], int len) { for (int i = 0;i < len;i++) { rev[i] = rev[i >> 1] >> 1; if (i & 1) // 如果最后一位是 1,则翻转成 len/2 rev[i] |= len >> 1; } for (int i = 0;i < len;i++) { rev[i] = rev[i >> 1] >> 1; if (i & 1) // 如果最后一位是 1,则翻转成 len/2 rev[i] |= len >> 1; } for (int i = 0;i < len;i++) if (i < rev[i]) // 保证每对数只翻转一次 swap(y[i], y[rev[i]]); swap(y[i], y[rev[i]]);}
/** 做 FFT* len 必须是 2^k 形式* on == 1 时是 DFT,on == -1 时是 IDFT*/void fft(Complex y[], int len, int on) { change(y, len); for (int h = 2;h <= len;h <<= 1) { Complex wn(cos(2 * PI / h), sin(on * 2 * PI / h)); for (int j = 0;j < len;j += h) { Complex w(1, 0); for (int k = j;k < j + h / 2;k++) { Complex u = y[k]; Complex t = w * y[k + h / 2]; y[k] = u + t; y[k + h / 2] = u - t; w = w * wn; } } } if (on == -1) for (int i = 0; i < len; i++) y[i].x /= len, y[i].y /= len;}```# 输入输出优化## 快读板子```cppinline int read() { // 快读 int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); change(y, len); for (int h = 2;h <= len;h <<= 1) { Complex wn(cos(2 * PI / h), sin(on * 2 * PI / h)); for (int j = 0;j < len;j += h) { Complex w(1, 0); for (int k = j;k < j + h / 2;k++) { Complex u = y[k]; Complex t = w * y[k + h / 2]; y[k] = u + t; y[k + h / 2] = u - t; w = w * wn; } } } return x * f; if (on == -1) for (int i = 0;i < len;i++) y[i].x /= len, y[i].y /= len;}```## 快写板子```cppinline void print(int x) { // 快写 if (x < 0) { putchar('-'); x = -x;## 快速数论变换(NTT)```cpp line-numbersvoid ntt(int *x, int lim, int opt) { int k, gn, g, tmp; for (int i = 0; i < lim; ++i) if (r[i] < i) swap(x[i], x[r[i]]); for (int m = 2;m <= lim;m <<= 1) { k = m >> 1; gn = qpow(3, (P - 1) / m); for (int i = 0;i < lim;i += m) { g = 1; for (int j = 0; j < k; ++j, g = 1ll * g * gn % P) { tmp = 1ll * x[i + j + k] * g % P; x[i + j + k] = (x[i + j] - tmp + P) % P; x[i + j] = (x[i + j] + tmp) % P; } } } if (x > 9) print(x / 10); putchar(x % 10 + '0'); if (opt == -1) { reverse(x + 1, x + lim); int inv = qpow(lim, P - 2); for (int i = 0;i < lim;i++) x[i] = 1ll * x[i] * inv % P; }}```# 字符串操作## 树的遍历```cpp```cpp line-numbersvoid pre(int x) { cout << x << " "; if (a[x][1]) pre(a[x][1]); if (a[x][2]) pre(a[x][2]); cout << x << " "; if (a[x][1]) pre(a[x][1]); if (a[x][2]) pre(a[x][2]);}
void in(int x) { if (a[x][1]) in(a[x][1]); cout << x << " "; if (a[x][2]) in(a[x][2]); if (a[x][1]) in(a[x][1]); cout << x << " "; if (a[x][2]) in(a[x][2]);}
void post(int x) { if (a[x][1]) post(a[x][1]); if (a[x][2]) post(a[x][2]); cout << x << " "; if (a[x][1]) post(a[x][1]); if (a[x][2]) post(a[x][2]); cout << x << " ";}```## 判断回文字符串```cpp```cpp line-numbersbool is_hw(string s) { int left = 0, right = s.size() - 1; while (left < right) { if (s[left] != s[right]) return false;3 行未改动 return true;}```## trie 字典树```cpp```cpp line-numbersint trie[N][MN];int tot, sum[N];
void insert(string s) { //插入一个字符串s int ls = s.size(); int root = 0; for (int i = 0; i < ls; i++) { int id = s[i] - 'a'; if (!trie[root][id]) trie[root][id] = ++tot; sum[trie[root][id]]++; root = trie[root][id]; } int ls = s.size(); int root = 0; for (int i = 0; i < ls; i++) { int id = s[i] - 'a'; if (!trie[root][id]) trie[root][id] = ++tot; sum[trie[root][id]]++; root = trie[root][id]; }}
int search(string s) { //查询某个字符串是否在字典中 int root = 0; int ls = s.size(); for (int i = 0; i < ls; i++) { int id = s[i] - 'a'; if (!trie[root][id]) return 0; root = trie[root][id]; } return sum[root]; int root = 0; int ls = s.size(); for (int i = 0; i < ls; i++) { int id = s[i] - 'a'; if (!trie[root][id]) return 0; root = trie[root][id]; } return sum[root];}
void del(string c) { int ls = c.size(); int root = 0, fa = search(c), t, id; for (int i = 0;i < ls;i++) { id = c[i] - 'a'; if (!trie[root][id]) return; t = root; root = trie[root][id]; sum[root] -= fa; } trie[t][id] = 0; sum[root] -= fa; int ls = c.size(); int root = 0, fa = search(c), t, id; for (int i = 0;i < ls;i++) { id = c[i] - 'a'; if (!trie[root][id]) return; t = root; root = trie[root][id]; sum[root] -= fa; } trie[t][id] = 0; sum[root] -= fa;}```## AC 自动机```cpp```cpp line-numbersnamespace AC { struct S { int son[27], ans, fail, du, id; void init() { memset(son, 0, sizeof(son)); ans = fail = id = 0; } } trie[N]; int ans[N], tot, pid; void init() { tot = pid = 0; trie[0].init(); } void insert(char s[], int &idx) { int u = 0; for (int i = 1;s[i];i++) { int &son = trie[u].son[s[i] - 'a']; if (!son) son = ++tot, trie[son].init(); u = son; } if (!trie[u].id) trie[u].id = ++pid; idx = trie[u].id; } void build() { queue <int> q; for (int i = 0;i < 26;i++) if (trie[0].son[i]) q.push(trie[0].son[i]); while (!q.empty()) { struct S { int son[27], ans, fail, du, id; void init() { memset(son, 0, sizeof(son)); ans = fail = id = 0; } } trie[N]; int ans[N], tot, pid; void init() { tot = pid = 0; trie[0].init(); } void insert(char s[], int &idx) { int u = 0; for (int i = 1;s[i];i++) { int &son = trie[u].son[s[i] - 'a']; if (!son) son = ++tot, trie[son].init(); u = son; } if (!trie[u].id) trie[u].id = ++pid; idx = trie[u].id; } void build() { queue <int> q; for (int i = 0;i < 26;i++) if (trie[0].son[i]) q.push(trie[0].son[i]); while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0;i < 26;i++) { if (trie[u].son[i]) { trie[trie[u].son[i]].fail = trie[trie[u].fail].son[i]; trie[trie[trie[u].fail].son[i]].du++; q.push(trie[u].son[i]); } else trie[u].son[i] = trie[trie[u].fail].son[i]; else trie[u].son[i] = trie[trie[u].fail].son[i]; } } } void query(char t[]) { int u = 0; for (int i = 1; t[i]; i++) { u = trie[u].son[t[i] - 'a']; trie[u].ans++; } } void topu() { queue <int> q; for (int i = 0;i <= tot;i++) if (trie[i].du == 0) q.push(i); } } void query(char t[]) { int u = 0; for (int i = 1; t[i]; i++) { u = trie[u].son[t[i] - 'a']; trie[u].ans++; } } void topu() { queue <int> q; for (int i = 0;i <= tot;i++) if (trie[i].du == 0) q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); ans[trie[u].id] = trie[u].ans; int v = trie[u].fail; trie[v].ans += trie[u].ans; if (!--trie[v].du) q.push(v); } } }}
int n, idx[N];char a[N], b[N];10 行未改动 return 0;}```## 回文自动机(PAM)```cpp```cpp line-numbersstruct Palindrome_Automaton { int ch[N][LN], fail[N], len[N], sum[N], cnt, last; Palindrome_Automaton() { cnt = 1; fail[0] = 1, fail[1] = 1, len[1] = -1; } int getfail(int x, int i) { while(i - len[x] - 1 < 0 || s[i - len[x] - 1] != s[i]) x = fail[x]; return x; } void insert(char c, int i) { int x = getfail(last, i), w = c - 'a'; if(!ch[x][w]) { len[++cnt] = len[x] + 2; int tmp = getfail(fail[x], i); fail[cnt] = ch[tmp][w]; sum[cnt] = sum[fail[cnt]] + 1; ch[x][w] = cnt; } last = ch[x][w]; } int ch[N][LN], fail[N], len[N], sum[N], cnt, last; Palindrome_Automaton() { cnt = 1; fail[0] = 1, fail[1] = 1, len[1] = -1; } int getfail(int x, int i) { while(i - len[x] - 1 < 0 || s[i - len[x] - 1] != s[i]) x = fail[x]; return x; } void insert(char c, int i) { int x = getfail(last, i), w = c - 'a'; if(!ch[x][w]) { len[++cnt] = len[x] + 2; int tmp = getfail(fail[x], i); fail[cnt] = ch[tmp][w]; sum[cnt] = sum[fail[cnt]] + 1; ch[x][w] = cnt; } last = ch[x][w]; }} PAM;
signed main() { cin >> (s + 1); int len = strlen(s + 1); for (int i = 1;i <= len;i++) { s[i] = (s[i] - 97 + ans) % 26 + 97; PAM.insert(s[i], i); cout << (ans = PAM.sum[PAM.last]) << " "; } cout << endl; return 0; cin >> (s + 1); int len = strlen(s + 1); for (int i = 1;i <= len;i++) { s[i] = (s[i] - 97 + ans) % 26 + 97; PAM.insert(s[i], i); cout << (ans = PAM.sum[PAM.last]) << " "; } cout << endl; return 0;}```## Manacher 最长回文串```cpp```cpp line-numbersstring s = "~|";char c;int p[N], ans, r = 0, mid = 0;
signed main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); while (cin >> c) s += c, s += '|'; for (int i = 0;i < (int)s.size();i++) { if (i <= r) p[i] = min(p[(mid << 1) - i], r - i + 1); while (s[i - p[i]] == s[i + p[i]]) p[i]++; if (p[i] + i > r) r = p[i] + i - 1, mid = i; if (p[i] > ans) ans = p[i]; if (i <= r) p[i] = min(p[(mid << 1) - i], r - i + 1); while (s[i - p[i]] == s[i + p[i]]) p[i]++; if (p[i] + i > r) r = p[i] + i - 1, mid = i; if (p[i] > ans) ans = p[i]; } cout << ans - 1 << endl; return 0;}```## 手写字符串 hash```cpp**热知识**:一定要用自己的模数,常用模数和自然溢出被卡遍了。```cpp line-numbersconst ull M = 1610612741, P = 131;
ull h[2000005];
ull Hash(string s) { h[0] = 0; int len = s.size(); for (int i = 1;i <= len;i++) h[i] = (h[i - 1] * P + s[i - 1]) % M; return h[len]; h[0] = 0; int len = s.size(); for (int i = 1;i <= len;i++) h[i] = (h[i - 1] * P + s[i - 1]) % M; return h[len];}
hash <string> _hash;```## 双模数 hash```cpp```cpp line-numbersconst ull mod1 = 1610612741, mod2 = 402653189, p = 131;
struct s { ull x, y; bool operator < (const s & a) const { bool operator < (s a) const { return a.x == x ? a.y < y : a.x < x; } bool operator > (const s & a) const { bool operator > (s a) const { return a.x == x ? a.y > y : a.x > x; }}h[maxn];} h[maxn];
inline ull hash1(string s) {ull hash1(string s) { ull ans = 0; for (int i = 1;i <= s.size();i++) ans = (ans * p + s[i]) % mod1; return ans;}
inline ull hash2(string s){ull hash2(string s){ ull ans = 0; for (int i = 1;i <= s.size();i++) ans = (ans * base + s[i]) % mod2; return ans;}```## 字符串任意子段 hash```cpp```cpp line-numbersull h[N], p[N]; void init_Hash(string s) { int n = s.size();7 行未改动 return h[pos + len] - h[pos] * p[len];}```## hash 质数表```cpp```cpp line-numbersull M[] = {0, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};```## 字符串 KMP```cpp```cpp line-numbersvector <int> prefix(string s) { int n = s.size(); vector <int> pi(n); for (int i = 1;i < n;i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; int n = s.size(); vector <int> pi(n); for (int i = 1;i < n;i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi;}
vector <int> kmp(string all, string pattern) { string cur = pattern + '`' + all; int size1 = all.size(), size2 = pattern.size(); vector <int> v, lps = prefix(cur); for (int i = size2 + 1;i <= size1 + size2;i++) { if (lps[i] == size2) v.push_back(i - 2 * size2); } return v; string cur = pattern + '`' + all; int size1 = all.size(), size2 = pattern.size(); vector <int> v, lps = prefix(cur); for (int i = size2 + 1;i <= size1 + size2;i++) { if (lps[i] == size2) v.push_back(i - 2 * size2); } return v;}```# 图论算法## SPFA 最短路```cpp```cpp line-numbersint dis[N];int h[N], to[N], val[N], nxt[N], cnt, n, m, s;int cnt_in_queue[N];bool vis[N];11 行未改动
queue <int> q; q.push(s); vis[s] = true; cnt_in_queue[s]++; tot[s]++;
while (!q.empty()) { int u = q.front(); q.pop();8 行未改动
if (!vis[v]) { q.push(v); vis[v] = true; cnt_in_queue[v]++; tot[v]++;
if (cnt_in_queue[v] > n) return true; if (tot[v] > n) return true; } } } }10 行未改动 add(a, b, c); }
bool circle = spfa(s, n); if (circle) cout << "Graph contains a negative weight cycle!" << endl; if (!circle) ;// 处理负环 return 0;}```## SPFA 优化版(SLF + LLL + 随机化)```cpp```cpp line-numbersint dis[N];int h[N], to[N], val[N], nxt[N], cnt, n, m, s, t;int cnt_in_queue[N];int h[N], to[N], val[N], nxt[N], tot[N], cnt, n, m, s, t, x, y, z;bool vis[N];
void add(int a, int b, int c) { to[++cnt] = b;2 行未改动 h[a] = cnt;}
bool optimized_spfa(int s, int n) { for (int i = 1;i <= ::n;i++) dis[i] = INF; for (int i = 1;i <= ::n;i++) dis[i] = inf; dis[s] = 0;
deque <int> q; q.push_back(s); vis[s] = true; cnt_in_queue[s]++; tot[s]++; long long sum = dis[s]; int q_size = 1; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());2 行未改动 if (q.size() > 1 && rng() % 10 == 0) swap(q.front(), q.back());
int u = q.front(); q.pop_front(); while (q_size > 1 && (long long)dis[u] * q_size > sum + 100) { int lllCount = 0; while (qSize > 1 && dist[u] * qSize > sum + 100) { if (++lllCount > qSize * 2) break; q.push_back(u); u = q.front(); q.pop_front(); }20 行未改动 vis[v] = true; sum += dis[v]; q_size++; cnt_in_queue[v]++; tot[v]++; if (cnt_in_queue[v] > n) return true; if (tot[v] > n) return true; } else sum += dis[v]; } } } return false;}```## SPFA Hack 数据生成器```cpp```cpp line-numbersunsigned long long get_seed() { auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count()); auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast <chrono::nanoseconds>(now.time_since_epoch()); return static_cast <unsigned long long> (timestamp.count());}
mt19937_64 mt(get_seed());
8 行未改动}
void generate_hack_data() { const int n = 50000; // 节点数 const int m = 500000; // 边数 int n = 50000; // 节点数 int m = 500000; // 边数 cout << n << " " << m << endl; // 1. 构造主链(权值为1的边) for(int i = 1; i < n; ++i) { for(int i = 1;i < n;i++) { cout << i << " " << i+1 << " " << 1 << endl; } // 2. 添加大量高权值反向边和随机边 mt19937 rng(time(0)); for(int i = 0; i < m - (n-1); ++i) { for(int i = 0;i < m - (n - 1);i++) { int u = rng() % n + 1; int v = rng() % n + 1; if(u == v) v = v % n + 1; // 避免自环 if (u == v) v = v % n + 1; // 避免自环 // 随机决定是添加反向边还是随机边 if(rng() % 3 == 0 && u > 1) { // 添加高权值反向边(针对SLF优化) cout << u << " " << u-1 << " " << Rand(1e18) + 1 << endl; } else { else { // 添加随机边(针对LLL优化) if(u > v) swap(u, v); cout << u << " " << v << " " << Rand(1e6) << endl; }12 行未改动 return 0;}```## Bellman-Ford 最短路```cpp```cpp line-numbersstruct Edge { int u, v, w;};
3 行未改动bool bellman_ford(int s, int n) { memset(dis, 0x7f, sizeof(dis)); dis[s] = 0; for (int i = 1;i < n;i++) { bool updated = false; bool f = false; for (auto edge : edges) { int u = edge.u; int v = edge.v; int w = edge.w;
if (dis[u] != INF && dis[v] > dis[u] + w) { dis[v] = dis[u] + w; updated = true; } if (dis[u] != INF && dis[v] > dis[u] + w) dis[v] = dis[u] + w, f = true; } if (!updated) break; if (!f) break; }
for (const auto& edge : edges) { for (auto edge : edges) { int u = edge.u; int v = edge.v; int w = edge.w;
if (dis[u] != inf && dis[v] > dis[u] + w) { return false; } if (dis[u] != inf && dis[v] > dis[u] + w) return false; }
return true;}9 行未改动 }
bool circle = bellman_ford(s, n);
if (!circle) cout << "Graph contains a negative weight cycle!" << endl; if (!circle) ;// 处理负环 return 0;}```## Dijkstra 最短路```cpp```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z, s, t;bool vis[N];
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; } int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
std::priority_queue <node> q;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
void Dijkstra(int s) { for (int i = 1;i <= n;i++) dis[i] = inf; dis[s] = 0; tmp.v = s, tmp.w = 0; q.push(tmp); while (!q.empty()) { int u = q.top().v; q.pop(); if (vis[u]) continue; vis[u] = 1; for (int i = h[u];i;i = nxt[i]) { if (dis[to[i]] > dis[u] + val[i]) { dis[to[i]] = dis[u] + val[i]; tmp.w = dis[to[i]], tmp.v = to[i]; q.push(tmp); } } } for (int i = 1;i <= n;i++) dis[i] = inf; dis[s] = 0; tmp.v = s, tmp.w = 0; q.push(tmp); while (!q.empty()) { int u = q.top().v; q.pop(); if (vis[u]) continue; vis[u] = 1; for (int i = h[u];i;i = nxt[i]) { if (dis[to[i]] > dis[u] + val[i]) { dis[to[i]] = dis[u] + val[i]; tmp.w = dis[to[i]], tmp.v = to[i]; q.push(tmp); } } }}
signed main() { cin >> n >> m; cin >> n >> m; for (int i = 1;i <= m;i++) cin >> x >> y >> z, add(x, y, z), add(y, x, z); cin >> s >> t; Dijkstra(s); cout << dis[t] << endl; return 0;}```## Floyd 最短路```cpp```cpp line-numbersint n, m, x, y, z, dp[N][N];
void Floyd() { for (int k = 1;k <= n;k++) for (int i = 1;i <= n;i++) for (int j = 1;j <= n;j++) if (i != j && j != k && i != k) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); for (int k = 1;k <= n;k++) for (int i = 1;i <= n;i++) for (int j = 1;j <= n;j++) if (i != j && j != k && i != k) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);}
memset(dp, 0x7f, sizeof(dp));memset(dp, 0x3f, sizeof(dp));```## 最小生成树(Prim)```cpp## Prim 最小生成树```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], ans, cnt, n, m;bool vis[N];
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; } int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
priority_queue <node> q;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
void Prim() { for (int i = 2;i <= n;i++) dis[i] = 0x7fffffff; q.push((node){1, 0}); while (!q.empty() || cnt < n - 1) { node x = q.top(); q.pop(); if (vis[x.v]) continue; for (int i = 2;i <= n;i++) dis[i] = 0x7fffffff; q.push((node){1, 0}); while (!q.empty() || cnt < n - 1) { node x = q.top(); q.pop(); if (vis[x.v]) continue; vis[x.v] = true; ans += x.w; cnt++; for (int i = h[x.v];i;i = nxt[i]) { if (dis[to[i]] > val[i]) { dis[to[i]] = val[i]; q.push((node){to[i], dis[to[i]]}); if (dis[to[i]] > val[i]) { dis[to[i]] = val[i]; q.push((node){to[i], dis[to[i]]}); } } }}
signed main() { int u, v, w; cin >> n >> m; cin >> n >> m; for (int i = 1;i <= m;i++) { cin >> u >> v >> w; add(u, v, w); add(v, u, w);6 行未改动 cout << ans << endl; return 0;}```## 最小生成树(Kruskal)```cpp## Kruskal 最小生成树```cpp line-numbersstruct Edge { int u, v, w; bool operator < (const Edge& other) const { return w < other.w;15 行未改动 if (rootX != rootY) parent[rootX] = rootY;}
void kruskal(int n) { for (int i = 1;i <= n;++i) parent[i] = i; for (int i = 1;i <= n;i++) parent[i] = i;
sort(edges.begin(), edges.end());
int mst_weight = 0;7 行未改动 if (find(u) != find(v)) { unite(u, v); mst_weight += w; selected_edges++;// cout << "Selected edge: " << u << " - " << v << " with weight " << w << endl;// cout << "Selected edge: " << u << " - " << v << " with weight " << w << endl;
if (selected_edges == n - 1) break; } }
// cout << "Total weight of MST: " << mst_weight << endl;// cout << "Total weight of MST: " << mst_weight << endl;}
signed main() { int n, m;14 行未改动int incf[N], h[N], to[N], val[N], nxt[N], pre[N], cnt, n, m, x, y, z, s, t, maxflow;bool vis[N];
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = a; val[cnt] = 0; nxt[cnt] = h[b]; h[b] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = a; val[cnt] = 0; nxt[cnt] = h[b]; h[b] = cnt;}
void update(int s, int t, int &maxflow) { int x = t; while (x != s) { int i = pre[x]; val[i] -= incf[t]; val[i ^ 1] += incf[t]; x = to[i ^ 1]; } maxflow += incf[t]; int x = t; while (x != s) { int i = pre[x]; val[i] -= incf[t]; val[i ^ 1] += incf[t]; x = to[i ^ 1]; } maxflow += incf[t];}
bool bfs(int s, int t) { memset(vis, 0, sizeof(vis)); deque <int> q; q.push_back(s); incf[s] = inf; while (!q.empty()) { int x = q.front(); q.pop_front(); for (int i = h[x];i;i = nxt[i]) { if (val[i]) { int y = to[i]; if (vis[y]) continue; incf[y] = min(incf[x], val[i]); pre[y] = i; q.push_back(y); vis[y] = 1; if (y == t) return 1; } } } return 0; memset(vis, 0, sizeof(vis)); deque <int> q; q.push_back(s); incf[s] = inf; while (!q.empty()) { int x = q.front(); q.pop_front(); for (int i = h[x];i;i = nxt[i]) { if (val[i]) { int y = to[i]; if (vis[y]) continue; incf[y] = min(incf[x], val[i]); pre[y] = i; q.push_back(y); vis[y] = 1; if (y == t) return 1; } } } return 0;}
signed main() {// memset(h, 0, sizeof(h)); cin >> n >> m >> s >> t; cnt = 1, maxflow = 0; for (int i = 1;i <= m;i++) cin >> x >> y >> z, add(x, y, z); while (bfs(s, t)) update(s, t, maxflow); cout << maxflow << endl;// memset(h, 0, sizeof(h)); cin >> n >> m >> s >> t; cnt = 1, maxflow = 0; for (int i = 1;i <= m;i++) cin >> x >> y >> z, add(x, y, z); while (bfs(s, t)) update(s, t, maxflow); cout << maxflow << endl; return 0;}```## Dinic 网络最大流```cpp```cpp line-numbersint h[N], to[N], val[N], nxt[N], dis[N], now[N], cnt, n, m, x, y, z, s, t, maxflow, flow;
void add(int a, int b, int c) { to[++cnt] = b;59 行未改动 return 0;}```## Dinic 二分图匹配```cpp```cpp line-numbersint h[N], to[N], val[N], nxt[N], dis[N], now[N], cnt = 1, n, m, x, y, z, s, t, maxflow, flow;
void add(int a, int b, int c) { to[++cnt] = b;46 行未改动 return flow - rest;}```## tarjan 割边 / 割点```cpp```cpp line-numbersint dfn[N], low[N], dfncnt, tot;int dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z;map <int, bool> cut_v;map <pair <int, int>, bool> cut_e;bool vis[N];
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
void tarjan_cut(int fa, int root, int u) { low[u] = dfn[u] = ++dfncnt; int flag = 0; for (int i = h[u];i;i = nxt[i]) { int v = to[i]; if (!dfn[v]) { tarjan_cut(u, root, v); low[u] = min(low[u], low[v]); if (low[v] >= dfn[u] && u != root) cut_v[u] = 1; if (low[v] > dfn[u]) cut_e[{min(u, v), max(u, v)}] = 1; if (root == u) flag++; } else low[u] = min(low[u], dfn[v]); low[u] = dfn[u] = ++dfncnt; int flag = 0; for (int i = h[u];i;i = nxt[i]) { int v = to[i]; if (!dfn[v]) { tarjan_cut(u, root, v); low[u] = min(low[u], low[v]); if (low[v] >= dfn[u] && u != root) cut_v[u] = 1; if (low[v] > dfn[u]) cut_e[{min(u, v), max(u, v)}] = 1; if (root == u) flag++; } else low[u] = min(low[u], dfn[v]); } if (flag >= 2 && u == root) cut_v[u] = 1;}```## tarjan 强连通分量```cpp```cpp line-numbersint dfn[N], low[N], tot, dfncnt;int dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z;bool vis[N];stack <int> S;
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
void tarjan(int u) { low[u] = dfn[u] = ++dfncnt, vis[u] = 1; S.push(u); for (int i = h[u];i;i = nxt[i]) { int v = to[i]; if (dfn[v] == 0) tarjan(v), low[u] = min(low[u], low[v]); else if (vis[v]) low[u] = min(low[u], dfn[v]); low[u] = dfn[u] = ++dfncnt, vis[u] = 1; S.push(u); for (int i = h[u];i;i = nxt[i]) { int v = to[i]; if (dfn[v] == 0) tarjan(v), low[u] = min(low[u], low[v]); else if (vis[v]) low[u] = min(low[u], dfn[v]); } if (dfn[u] == low[u]) { tot++; while (1) {5 行未改动 }}```## 拓扑排序```cpp```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z;int in[N];bool vis[N];
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
vector <int> topoSort() { vector <int> topoOrder;18 行未改动 return topoOrder;}```## 最近公共祖先(LCA)### 倍增法```cppint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z, ans;```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, s, x, y, z, ans;int f[N][32], cost[N][32], dep[N];bool is_find;map <int, bool> vis;
struct node { int v, w; friend bool operator < (node a, node b) { return a.w > b.w; } friend bool operator > (node a, node b) { return a.w < b.w; }} tmp;
void add(int a, int b, int c) { to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt; to[++cnt] = b; val[cnt] = c; nxt[cnt] = h[a]; h[a] = cnt;}
void dfs(int root, int fa) { f[root][0] = fa; dep[root] = dep[f[root][0]] + 1; for (int i = 1;i <= 31;i++) { f[root][i] = f[f[root][i - 1]][i - 1]; cost[root][i] = cost[f[root][i - 1]][i - 1] + cost[root][i - 1]; } for (int u = h[root];u;u = nxt[u]) { int v = to[u]; if (v == fa) continue; cost[v][0] = val[u]; dfs(v, root); } f[root][0] = fa; dep[root] = dep[f[root][0]] + 1; for (int i = 1;i <= 31;i++) { f[root][i] = f[f[root][i - 1]][i - 1]; cost[root][i] = cost[f[root][i - 1]][i - 1] + cost[root][i - 1]; } for (int u = h[root];u;u = nxt[u]) { int v = to[u]; if (v == fa) continue; cost[v][0] = val[u]; dfs(v, root); }}
int lca_cost(int x, int y) { if (dep[x] > dep[y]) swap(x, y); int temp = dep[y] - dep[x], ans = 0; for (int j = 0;temp;temp >>= 1, j++) if (temp & 1) ans += cost[y][j], y = f[y][j]; if (y == x) return ans; for (int j = 30;j >= 0 && y != x;j--) if (f[x][j] != f[y][j]) ans += cost[x][j] + cost[y][j], x = f[x][j], y = f[y][j]; ans += cost[x][0] + cost[y][0]; return ans;}
int lca(int x, int y) { if (dep[x] > dep[y]) swap(x, y); int temp = dep[y] - dep[x], ans = 0; for (int j = 0;temp;temp >>= 1, j++) if (temp & 1) ans += cost[y][j], y = f[y][j]; if (y == x) return ans; for (int j = 30;j >= 0 && y != x;j--) if (f[x][j] != f[y][j]) ans += cost[x][j] + cost[y][j], x = f[x][j], y = f[y][j]; ans += cost[x][0] + cost[y][0]; return ans; if (dep[x] > dep[y]) swap(x, y); int temp = dep[y] - dep[x]; for (int j = 0;temp;temp >>= 1, j++) if (temp & 1) y = f[y][j]; if (y == x) return x; for (int j = 30;j >= 0;j--) if (f[x][j] != f[y][j]) x = f[x][j], y = f[y][j]; return f[x][0];}```### DFS 法```cpp line-numbersint get(int x, int y) { return dfn[x] < dfn[y] ? x : y;}
void dfs(int u, int fa) { dfn[u] = ++tot; st[0][dfn[u]] = fa; dep[u] = dep[fa] + 1; for (int i = h[u];i;i = nxt[i]) { int v = to[i]; if (v == fa) continue; dfs(v, u); }}
void init() { dfs(s, 0); for (int i = 1;i <= 22;i++) for (int j = 1;j + ((1 << i) - 1) <= tot;j++) st[i][j] = get(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);}
int lca(int u, int v) { if (u == v) return u; int x = dfn[u], y = dfn[v]; if (x > y) swap(x, y); int d = __lg(y - x); return get(st[d][x + 1], st[d][y - (1 << d) + 1]);}```# 小型数据结构## 并查集```cpp```cpp line-numbersint f[N];
int find(int x) { if (f[x] == x) return x; return f[x] = find(f[x]); if (f[x] == x) return x; return f[x] = find(f[x]);}
void merge(int x, int y) { int fx = find(x), fy = find(y); if (fx != fy) f[fx] = fy; int fx = find(x), fy = find(y); if (fx != fy) f[fx] = fy;}```## ST 表```cpp```cpp line-numbers#include <iostream>using namespace std;
const int N = 2e5 + 2, Logn = 22;
int a[N][Logn], b[N][Logn], logn[N], n, m; // a 表示最大值,b 表示最小值
signed main() { ios::sync_with_stdio(0); cin.tie(), cout.tie(); cin >> n >> m; for (int i = 1;i <= n;i++) cin >> a[i][0], b[i][0] = a[i][0]; logn[1] = 0, logn[2] = 1; for (int i = 3;i < N;i++) logn[i] = logn[i / 2] + 1; for (int i = 1;i <= Logn;i++) for (int j = 1;j + (1 << i) - 1 <= n;j++) a[j][i] = max(a[j][i - 1], a[j + (1 << (i - 1))][i - 1]), b[j][i] = min(b[j][i - 1], b[j + (1 << (i - 1))][i - 1]); for (int i = 1;i <= m;i++) { int x, y; cin >> x >> y; int mid = logn[y - x + 1]; cout << max(a[x][mid], a[y - (1 << mid) + 1][mid]) << " " << min(b[x][mid], b[y - (1 << mid) + 1][mid]) << '\n'; } return 0; ios::sync_with_stdio(0); cin.tie(), cout.tie(); cin >> n >> m; for (int i = 1;i <= n;i++) cin >> a[i][0], b[i][0] = a[i][0]; logn[1] = 0, logn[2] = 1; for (int i = 3;i < N;i++) logn[i] = logn[i / 2] + 1; for (int i = 1;i <= Logn;i++) for (int j = 1;j + (1 << i) - 1 <= n;j++) a[j][i] = max(a[j][i - 1], a[j + (1 << (i - 1))][i - 1]), b[j][i] = min(b[j][i - 1], b[j + (1 << (i - 1))][i - 1]); for (int i = 1;i <= m;i++) { int x, y; cin >> x >> y; int mid = logn[y - x + 1]; cout << max(a[x][mid], a[y - (1 << mid) + 1][mid]) << " " << min(b[x][mid], b[y - (1 << mid) + 1][mid]) << '\n'; } return 0;}```# 树形数据结构## 树状数组```cpp```cpp line-numbersint s[N];
inline int lowbit(int x) {return x & (-x);}int lowbit(int x) {return x & (-x);}
void modify(int p, int v) { for(;p <= n;p += lowbit(p)) s[p] += v;}4 行未改动 return res;}```## 线段树(指针版)```cpp```cpp line-numbersint n, m, mod = inf;int a[N];
struct Segment_Tree {221 行未改动全部展开 pushdown(node); int left_count = min(node -> right -> r, y) - max(node -> right -> l, x) + 1; if (left_count >= k) return query_kth_smallest(node -> left, x, y, k); else return query_kth_smallest(node -> right, x, y, k - left_count); else return query_kth_smallest(node -> right, x, y, k - left_count); } pushdown(node); int mid = (node -> l + node -> r) >> 1;66 行未改动 left -> l = node -> l; left -> r = pos - 1; if (left -> l <= left -> r) { left -> sum = node -> sum; left -> prod = node -> prod; left -> prod = node -> prod; left -> min_val = node -> min_val; left -> max_val = node -> max_val; left -> gcd_val = node -> gcd_val; left -> xor_sum = node -> xor_sum; left -> and_val = node -> and_val; left -> or_val = node -> or_val; } else { else { delete left; left = nullptr; } 20 行未改动 right -> xor_sum = node -> xor_sum; right -> and_val = node -> and_val; right -> or_val = node -> or_val; } else { else { delete right; right = nullptr; } 8 行未改动
pushdown(node); if (pos <= node -> left -> r) insert(node -> left, pos, k, val); else insert(node -> right, pos, k, val); else insert(node -> right, pos, k, val); node -> r += k; pushup(node);}190 行未改动全部展开signed main() { Segment_Tree *tree = new Segment_Tree;
delete_tree(tree); return 0; return 0;}```## 线段树(数组版)```cpp```cpp line-numbersint n, m, mod = inf;int a[N];
struct Segment_Tree {366 行未改动全部展开 return 0;}```## 线段树(加法版)```cpp```cpp line-numbersint n, m, mod;int a[N];
struct Segment_Tree { int sum, add; int l, r;} s[N * 4];} s[N << 2];
void pushup(int pos) { s[pos].sum = (s[pos << 1].sum + s[pos << 1 | 1].sum) % mod;}53 行未改动 return val;}```## 线段树(最小值版)```cpp```cpp line-numbersstruct Segment_Tree { int add; int min_val; int l, r;} s[N << 2];
inline void pushup(int pos) {void pushup(int pos) { s[pos].min_val = min(s[pos << 1].min_val, s[pos << 1 | 1].min_val);}
inline void pushdown(int pos) {void pushdown(int pos) { s[pos << 1].min_val += s[pos].add; s[pos << 1].add += s[pos].add;
s[pos << 1 | 1].min_val += s[pos].add; s[pos << 1 | 1].add += s[pos].add;
s[pos].add = 0;}
inline void build(int pos, int l, int r) {void build(int pos, int l, int r) { s[pos].l = l; s[pos].r = r; s[pos].add = 0;
7 行未改动 build(pos << 1 | 1, mid + 1, r); pushup(pos);}
inline void add(int pos, int x, int y, int k) {void add(int pos, int x, int y, int k) { if (x <= s[pos].l && s[pos].r <= y) { s[pos].min_val += k; s[pos].add += k; return;5 行未改动 if (y > mid) add(pos << 1 | 1, x, y, k); pushup(pos);}
inline int query_min(int pos, int x, int y) {int query_min(int pos, int x, int y) { if (x <= s[pos].l && s[pos].r <= y) return s[pos].min_val;
pushdown(pos); int mid = (s[pos].l + s[pos].r) >> 1;3 行未改动 return res;}```## gcd 线段树by @xhxxwcr.```cppstruct SegmentTree { struct Node { int sum, g; } tree[4 * N]; int n; vector <int> b;```cpp line-numbersint n, b[N];
void pushup(int pos) { tree[pos].sum = tree[pos << 1].sum + tree[pos << 1 | 1].sum; tree[pos].g = gcd(tree[pos << 1].g, tree[pos << 1 | 1].g); }struct Segment_Tree { int sum; int g;} s[N << 2];
void build(int pos, int l, int r) { if (l == r) { tree[pos].sum = b[l]; tree[pos].g = b[l]; return; } int mid = (l + r) >> 1; build(pos << 1, l, mid); build(pos << 1 | 1, mid + 1, r); pushup(pos); }void pushup(int pos) { s[pos].sum = s[pos << 1].sum + s[pos << 1 | 1].sum; s[pos].g = __gcd(s[pos << 1].g, s[pos << 1 | 1].g);}
void update(int pos, int l, int r, int index, int delta) { if (l == r) { tree[pos].sum += delta; tree[pos].g = tree[pos].sum; return; } int mid = (l + r) >> 1; if (index <= mid) update(pos << 1, l, mid, index, delta); else update(pos << 1| 1, mid + 1, r, index, delta); pushup(pos);void build(int pos, int l, int r) { if (l == r) { s[pos].sum = b[l]; s[pos].g = b[l]; return; } int mid = (l + r) >> 1; build(pos << 1, l, mid); build(pos << 1 | 1, mid + 1, r); pushup(pos);}
int query_sum(int pos, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) return tree[pos].sum; int mid = (l + r) >> 1; int res = 0; if (ql <= mid) res += query_sum(pos << 1, l, mid, ql, qr); if (qr > mid) res += query_sum(pos << 1 | 1, mid + 1, r, ql, qr); return res;void update(int pos, int l, int r, int index, int delta) { if (l == r) { s[pos].sum += delta; s[pos].g = s[pos].sum; return; } int mid = (l + r) >> 1; if (index <= mid) update(pos << 1, l, mid, index, delta); else update(pos << 1 | 1, mid + 1, r, index, delta); pushup(pos);}
int query_gcd(int pos, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) return tree[pos].g; int mid = (l + r) >> 1; if (qr <= mid) return query_gcd(pos << 1, l, mid, ql, qr); else if (ql > mid) return query_gcd(pos << 1 | 1, mid+1, r, ql, qr); else { int left_g = query_gcd(pos << 1, l, mid, ql, mid); int right_g = query_gcd(pos << 1 | 1, mid + 1, r, mid + 1, qr); return gcd(left_g, right_g); } }int query_sum(int pos, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) return s[pos].sum; int mid = (l + r) >> 1; int res = 0; if (ql <= mid) res += query_sum(pos << 1, l, mid, ql, qr); if (qr > mid) res += query_sum(pos << 1 | 1, mid + 1, r, ql, qr); return res;}
SegmentTree(int _n, vector <int> &a) { n = _n; b.resize(n); if (n > 0) { b[1] = a[1]; for (int i = 1;i < n;i++) { b[i] = a[i] - a[i-1]; } } build(1, 1, n-1);int query_gcd(int pos, int l, int r, int ql, int qr) { if (ql <= l && r <= qr) return s[pos].g; int mid = (l + r) >> 1; if (qr <= mid) return query_gcd(pos << 1, l, mid, ql, qr); else if (ql > mid) return query_gcd(pos << 1 | 1, mid + 1, r, ql, qr); else { int left_g = query_gcd(pos << 1, l, mid, ql, mid); int right_g = query_gcd(pos << 1 | 1, mid + 1, r, mid + 1, qr); return __gcd(left_g, right_g); }}
void change(int l, int r, int d) { update(1, 1, n, l, d); if (r + 1 < n) update(1, 1, n, r + 1, -d); }void init(int _n, int a[]) { n = _n; b[1] = a[1]; for (int i = 2;i <= n;i++) b[i] = a[i] - a[i - 1]; build(1, 1, n);}
int query(int l, int r) { if (l == r) { int x = query_sum(1, 0, n - 1, 0, l); return gcd(x, 0); } else { int x = query_sum(1, 0, n - 1, 0, l); int g = 0; if (l + 1 <= r) g = query_gcd(1, 0, n - 1, l + 1, r); return gcd(x, g); } }};void add(int l, int r, int d) { update(1, 1, n, l, d); if (r + 1 <= n) update(1, 1, n, r + 1, -d);}
int q_gcd(int l, int r) { int a_l = query_sum(1, 1, n, 1, l); if (l == r) return __gcd(a_l, 0); int tail_g = query_gcd(1, 1, n, l + 1, r); return __gcd(a_l, tail_g);}```## 可持久化线段树(主席树)- 指针版```cpp```cpp line-numbersint n, m, mod = inf;int a[N];vector <int> sorted; // 用于离散化的排序数组
497 行未改动全部展开 return 0;}```## 可持久化线段树(主席树)- 数组版```cpp```cpp line-numbersint n, m, mod = inf;int a[N];vector <int> sorted; // 离散化数组
321 行未改动全部展开 return 0;}```## Treap```cpp```cpp line-numbersint na;int ch[N][2];int val[N], dat[N];int sz[N], cnt[N];109 行未改动全部展开}```## Splay 伸展树from oi-wiki```cpp```cpp line-numbersint n, id, rt;int fa[N], val[N], cnt[N], sz[N], ch[N][2];
bool dir(int x) { return x == ch[fa[x]][1]; return x == ch[fa[x]][1];}
void push_up(int x) { sz[x] = cnt[x] + sz[ch[x][0]] + sz[ch[x][1]]; sz[x] = cnt[x] + sz[ch[x][0]] + sz[ch[x][1]];}
void rotate(int x) { int y = fa[x], z = fa[y]; bool r = dir(x); ch[y][r] = ch[x][!r]; ch[x][!r] = y; if (z) ch[z][dir(y)] = x; if (ch[y][r]) fa[ch[y][r]] = y; fa[y] = x; fa[x] = z; push_up(y); push_up(x); int y = fa[x], z = fa[y]; bool r = dir(x); ch[y][r] = ch[x][!r]; ch[x][!r] = y; if (z) ch[z][dir(y)] = x; if (ch[y][r]) fa[ch[y][r]] = y; fa[y] = x; fa[x] = z; push_up(y); push_up(x);}
void splay(int& z, int x) { int w = fa[z]; for (int y;(y = fa[x]) != w;rotate(x)) if (fa[y] != w) rotate(dir(x) == dir(y) ? y : x); z = x; int w = fa[z]; for (int y;(y = fa[x]) != w;rotate(x)) if (fa[y] != w) rotate(dir(x) == dir(y) ? y : x); z = x;}
void find(int& z, int v) { int x = z, y = fa[x]; for (;x && val[x] != v;x = ch[y = x][v > val[x]]); splay(z, x ? x : y); int x = z, y = fa[x]; for (;x && val[x] != v;x = ch[y = x][v > val[x]]); splay(z, x ? x : y);}
void loc(int& z, int k) { int x = z; for (;;) { if (sz[ch[x][0]] >= k) x = ch[x][0]; else if (sz[ch[x][0]] + cnt[x] >= k) break; else { k -= sz[ch[x][0]] + cnt[x]; x = ch[x][1]; } } splay(z, x); int x = z; for (;;) { if (sz[ch[x][0]] >= k) x = ch[x][0]; else if (sz[ch[x][0]] + cnt[x] >= k) break; else { k -= sz[ch[x][0]] + cnt[x]; x = ch[x][1]; } } splay(z, x);}
int merge(int x, int y) { if (!x || !y) return x | y; loc(y, 1); ch[y][0] = x; fa[x] = y; push_up(y); return y; if (!x || !y) return x | y; loc(y, 1); ch[y][0] = x; fa[x] = y; push_up(y); return y;}
void insert(int v) { int x = rt, y = 0; for (;x && val[x] != v;x = ch[y = x][v > val[x]]); if (x) { cnt[x]++; sz[x]++; } else { x = ++id; val[x] = v; cnt[x] = sz[x] = 1; fa[x] = y; if (y) ch[y][v > val[y]] = x; } splay(rt, x); int x = rt, y = 0; for (;x && val[x] != v;x = ch[y = x][v > val[x]]); if (x) { cnt[x]++; sz[x]++; } else { x = ++id; val[x] = v; cnt[x] = sz[x] = 1; fa[x] = y; if (y) ch[y][v > val[y]] = x; } splay(rt, x);}
bool remove(int v) { find(rt, v); if (!rt || val[rt] != v) return false; cnt[rt]--; sz[rt]--; if (!cnt[rt]) { int x = ch[rt][0]; int y = ch[rt][1]; fa[x] = fa[y] = 0; rt = merge(x, y); } return true; find(rt, v); if (!rt || val[rt] != v) return false; cnt[rt]--; sz[rt]--; if (!cnt[rt]) { int x = ch[rt][0]; int y = ch[rt][1]; fa[x] = fa[y] = 0; rt = merge(x, y); } return true;}
int find_rank(int v) { find(rt, v); return sz[ch[rt][0]] + (val[rt] < v ? cnt[rt] : 0) + 1; find(rt, v); return sz[ch[rt][0]] + (val[rt] < v ? cnt[rt] : 0) + 1;}
int find_kth(int k) { if (k > sz[rt]) return -1; loc(rt, k); return val[rt];int find_kth(int k) { // 第 k 小 if (k > sz[rt]) return -1; loc(rt, k); return val[rt];}
int find_prev(int v) { find(rt, v); if (rt && val[rt] < v) return val[rt]; int x = ch[rt][0]; if (!x) return -1; for (;ch[x][1];x = ch[x][1]); splay(rt, x); return val[rt]; find(rt, v); if (rt && val[rt] < v) return val[rt]; int x = ch[rt][0]; if (!x) return -1; for (;ch[x][1];x = ch[x][1]); splay(rt, x); return val[rt];}
int find_next(int v) { find(rt, v); if (rt && val[rt] > v) return val[rt]; int x = ch[rt][1]; if (!x) return -1; for (; ch[x][0]; x = ch[x][0]); splay(rt, x); return val[rt]; find(rt, v); if (rt && val[rt] > v) return val[rt]; int x = ch[rt][1]; if (!x) return -1; for (; ch[x][0]; x = ch[x][0]); splay(rt, x); return val[rt];}
int main() { cin >> n; while (n--) { int op, x; cin >> op >> x; switch (op) { case 1: insert(x); break; case 2: remove(x); break; case 3: cout << find_rank(x) << endl; break; case 4: cout << find_kth(x) << endl; break; case 5: cout << find_prev(x) << endl; break; case 6: cout << find_next(x) << endl; break; } } return 0; cin >> n; while (n--) { int op, x; cin >> op >> x; switch (op) { case 1: insert(x); break; case 2: remove(x); break; case 3: cout << find_rank(x) << endl; break; case 4: cout << find_kth(x) << endl; break; case 5: cout << find_prev(x) << endl; break; case 6: cout << find_next(x) << endl; break; } } return 0;}```## 树套树(线段树套 Splay)```cpp```cpp line-numbers// Splay Tree Node Structurestruct SplayNode { int val, cnt, sz; SplayNode *ch[2], *fa;16 行未改动 if (x -> ch[0]) x -> sz += x -> ch[0] -> sz; if (x -> ch[1]) x -> sz += x -> ch[1] -> sz; } void rotate(SplayNode* x) { SplayNode* y = x -> fa; SplayNode* z = y -> fa; int d = dir(x); y -> ch[d] = x -> ch[!d]; if (x -> ch[!d]) x -> ch[!d] -> fa = y; x -> fa = z; if (z) z -> ch[dir(y)] = x; x -> ch[!d] = y; y -> fa = x; push_up(y); push_up(x); } void rotate(SplayNode* x) { SplayNode* y = x -> fa; SplayNode* z = y -> fa; int d = dir(x); y -> ch[d] = x -> ch[!d]; if (x -> ch[!d]) x -> ch[!d] -> fa = y; x -> fa = z; if (z) z -> ch[dir(y)] = x; x -> ch[!d] = y; y -> fa = x; push_up(y); push_up(x); }
void splay(SplayNode* x) { while (x -> fa) { SplayNode* y = x -> fa; SplayNode* z = y -> fa; if (z) { if (dir(x) == dir(y)) rotate(y); else rotate(x); } rotate(x); } root = x; } void splay(SplayNode* x) { while (x -> fa) { SplayNode* y = x -> fa; SplayNode* z = y -> fa; if (z) { if (dir(x) == dir(y)) rotate(y); else rotate(x); } rotate(x); } root = x; }
SplayNode* find(int v) { SplayNode *x = root, *y = nullptr;37 行未改动
SplayTree() : root(nullptr) {} void insert(int v) { if (!root) { root = new SplayNode(v); return; } SplayNode* x = root; SplayNode* y = nullptr; while (x) { y = x; if (v == x -> val) { x -> cnt++; x -> sz++; splay(x); return; } x = x -> ch[v > x -> val]; } x = new SplayNode(v); y -> ch[v > y -> val] = x; x -> fa = y; splay(x); } void insert(int v) { if (!root) { root = new SplayNode(v); return; } SplayNode* x = root; SplayNode* y = nullptr; while (x) { y = x; if (v == x -> val) { x -> cnt++; x -> sz++; splay(x); return; } x = x -> ch[v > x -> val]; } x = new SplayNode(v); y -> ch[v > y -> val] = x; x -> fa = y; splay(x); } bool remove(int v) { SplayNode *x = find(v); if (!x || x -> val != v) return false;13 行未改动 return true; } int rank(int v) { int res = 0; SplayNode *x = root; while (x) { if (v < x -> val) x = x -> ch[0]; else { res += (x -> ch[0] ? x -> ch[0] -> sz : 0); if (v == x -> val) { splay(x); return res + 1; } res += x -> cnt; x = x -> ch[1]; } } return res + 1; } int res = 0; SplayNode *x = root; while (x) { if (v < x -> val) x = x -> ch[0]; else { res += (x -> ch[0] ? x -> ch[0] -> sz : 0); if (v == x -> val) { splay(x); return res + 1; } res += x -> cnt; x = x -> ch[1]; } } return res + 1; } int kth(int k) { int kth(int k) { // 第 k 小 SplayNode *x = root; while (x) { int lsz = x -> ch[0] ? x -> ch[0] -> sz : 0; if (k <= lsz) x = x -> ch[0];66 行未改动 update_val(root, pos, old_val, new_val); } int _query_kth(int l, int r, int k) { int left = 0, right = 1e8; int ans = 0; while (left <= right) { int mid = (left + right) / 2; int rank = _query_rank(root, l, r, mid) + 1; if (rank <= k) { ans = mid; left = mid + 1; } else right = mid - 1; } return ans; } int left = 0, right = 1e8; int ans = 0; while (left <= right) { int mid = (left + right) / 2; int rank = _query_rank(root, l, r, mid) + 1; if (rank <= k) { ans = mid; left = mid + 1; } else right = mid - 1; } return ans; } int _query_rank(SegmentNode *node, int l, int r, int val) { if (node -> r < l || node -> l > r) return 0; if (l <= node -> l && node -> r <= r) return node -> st.rank(val) - 1; return _query_rank(node -> left, l, r, val) + _query_rank(node -> right, l, r, val); } if (node -> r < l || node -> l > r) return 0; if (l <= node -> l && node -> r <= r) return node -> st.rank(val) - 1; return _query_rank(node -> left, l, r, val) + _query_rank(node -> right, l, r, val); } int _query_prev(SegmentNode *node, int l, int r, int val) { if (node -> r < l || node -> l > r) return -inf; if (l <= node -> l && node -> r <= r) return node -> st.prev(val);12 行未改动 return _query_rank(root, l, r, val) + 1; } int query_prev(int l, int r, int val) { int res = _query_prev(root, l, r, val); return res == -inf ? -2147483647 : res; } int query_kth(int l, int r, int val) { return _query_kth(l, r, val); } int query_next(int l, int r, int val) { int res = _query_next(root, l, r, val); return res == inf ? 2147483647 : res; } int res = _query_prev(root, l, r, val); return res == -inf ? -2147483647 : res; } int query_kth(int l, int r, int val) { return _query_kth(l, r, val); } int query_next(int l, int r, int val) { int res = _query_next(root, l, r, val); return res == inf ? 2147483647 : res; }
SegmentTree(int n, int *arr) : a(arr) { root = new SegmentNode(1, n); build(root, 1, n, arr);35 行未改动 return 0;}```## 笛卡尔树```cpp#include <bits/stdc++.h>#include <bits/extc++.h>#define int long long//#define endl "\n"#define debug printf("Running %s on line %d...\n", __FUNCTION__, __LINE__)#define ll long long#define ull unsigned long long#define str string#define db double#define ld long double#define si signed#define PQ priority_queue#define gcd(x, y) __gcd(x, y)#define Set(a) memset(a,0,sizeof(a))#define F(i,a,b) for(register int i=a,i##end=b;i<=i##end;++i)#define UF(i,a,b) for(register int i=a,i##end=b;i>=i##end;--i)#define Yes cout << "Yes" << endl#define No cout << "No" << endl#define YES cout << "YES" << endl#define NO cout << "NO" << endl#define yes cout << "yes" << endl#define no cout << "no" << endl#define O cout << -1 << endl#define E cout << endl#define elif else if#define _1 first#define _2 second#define fi first#define se second#define IO ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)using namespace std;using namespace __gnu_pbds;
const ull N = 1e7 + 2, inf = INT_MAX, dmax = INT_MAX, dmin = INT_MIN, mmax = 0x7f, minf = 0x7f7f7f7f;const ull lmax = LLONG_MAX, lmin = LLONG_MIN, ulmax = ULLONG_MAX;const ull M = 1610612741, P = 131, Mod = 998244353, Mod2 = 1e9 + 7;
```cpp line-numbersint p[N], l[N], r[N], n;
void build(int n) { stack <int> stk;17 行未改动 return 0;}```## 树链剖分```cpp```cpp line-numbers#define lc o << 1#define rc o << 1 | 1
int n, a, b, w[N], q, u, v;int cur, h[N], nxt[N], p[N];int siz[N], top[N], son[N], dep[N], fa[N], dfn[N], rnk[N], cnt;char op[10];
void add(int x, int y) { cur++; nxt[cur] = h[x]; h[x] = cur; p[cur] = y; cur++; nxt[cur] = h[x]; h[x] = cur; p[cur] = y;}
struct SegmentTree { int sum[N << 2], maxx[N << 2]; void build(int o, int l, int r) { if (l == r) { sum[o] = maxx[o] = w[rnk[l]]; return; } int mid = (l + r) >> 1; build(lc, l, mid); build(rc, mid + 1, r); sum[o] = sum[lc] + sum[rc]; maxx[o] = max(maxx[lc], maxx[rc]); } int query_max(int o, int l, int r, int ql, int qr) { if (l > qr || r < ql) return -inf; if (ql <= l && r <= qr) return maxx[o]; int mid = (l + r) >> 1; return max(query_max(lc, l, mid, ql, qr), query_max(rc, mid + 1, r, ql, qr)); } int query_sum(int o, int l, int r, int ql, int qr) { if (l > qr || r < ql) return 0; if (ql <= l && r <= qr) return sum[o]; int mid = (l + r) >> 1; return query_sum(lc, l, mid, ql, qr) + query_sum(rc, mid + 1, r, ql, qr); } void update(int o, int l, int r, int x, int t) { if (l == r) { maxx[o] = sum[o] = t; return; } int mid = (l + r) >> 1; if (x <= mid) update(lc, l, mid, x, t); else update(rc, mid + 1, r, x, t); sum[o] = sum[lc] + sum[rc]; maxx[o] = max(maxx[lc], maxx[rc]); } int sum[N << 2], maxx[N << 2]; void build(int o, int l, int r) { if (l == r) { sum[o] = maxx[o] = w[rnk[l]]; return; } int mid = (l + r) >> 1; build(lc, l, mid); build(rc, mid + 1, r); sum[o] = sum[lc] + sum[rc]; maxx[o] = max(maxx[lc], maxx[rc]); } int query_max(int o, int l, int r, int ql, int qr) { if (l > qr || r < ql) return -inf; if (ql <= l && r <= qr) return maxx[o]; int mid = (l + r) >> 1; return max(query_max(lc, l, mid, ql, qr), query_max(rc, mid + 1, r, ql, qr)); } int query_sum(int o, int l, int r, int ql, int qr) { if (l > qr || r < ql) return 0; if (ql <= l && r <= qr) return sum[o]; int mid = (l + r) >> 1; return query_sum(lc, l, mid, ql, qr) + query_sum(rc, mid + 1, r, ql, qr); } void update(int o, int l, int r, int x, int t) { if (l == r) { maxx[o] = sum[o] = t; return; } int mid = (l + r) >> 1; if (x <= mid) update(lc, l, mid, x, t); else update(rc, mid + 1, r, x, t); sum[o] = sum[lc] + sum[rc]; maxx[o] = max(maxx[lc], maxx[rc]); }}st;
void dfs1(int o) { son[o] = -1; siz[o] = 1; for (int j = h[o];j;j = nxt[j]) if (!dep[p[j]]) { dep[p[j]] = dep[o] + 1; fa[p[j]] = o; dfs1(p[j]); siz[o] += siz[p[j]]; if (son[o] == -1 || siz[p[j]] > siz[son[o]]) son[o] = p[j]; } son[o] = -1; siz[o] = 1; for (int j = h[o];j;j = nxt[j]) if (!dep[p[j]]) { dep[p[j]] = dep[o] + 1; fa[p[j]] = o; dfs1(p[j]); siz[o] += siz[p[j]]; if (son[o] == -1 || siz[p[j]] > siz[son[o]]) son[o] = p[j]; }}
void dfs2(int o, int t) { top[o] = t; cnt++; dfn[o] = cnt; rnk[cnt] = o; if (son[o] == -1) return; dfs2(son[o], t); for (int j = h[o];j;j = nxt[j]) if (p[j] != son[o] && p[j] != fa[o]) dfs2(p[j], p[j]); top[o] = t; cnt++; dfn[o] = cnt; rnk[cnt] = o; if (son[o] == -1) return; dfs2(son[o], t); for (int j = h[o];j;j = nxt[j]) if (p[j] != son[o] && p[j] != fa[o]) dfs2(p[j], p[j]);}
int query_max(int x, int y) { int ret = -inf, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret = max(ret, st.query_max(1, 1, n, dfn[fx], dfn[x])), x = fa[fx]; else ret = max(ret, st.query_max(1, 1, n, dfn[fy], dfn[y])), y = fa[fy]; fx = top[x]; fy = top[y]; } if (dfn[x] < dfn[y]) ret = max(ret, st.query_max(1, 1, n, dfn[x], dfn[y])); else ret = max(ret, st.query_max(1, 1, n, dfn[y], dfn[x])); return ret; int ret = -inf, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret = max(ret, st.query_max(1, 1, n, dfn[fx], dfn[x])), x = fa[fx]; else ret = max(ret, st.query_max(1, 1, n, dfn[fy], dfn[y])), y = fa[fy]; fx = top[x]; fy = top[y]; } if (dfn[x] < dfn[y]) ret = max(ret, st.query_max(1, 1, n, dfn[x], dfn[y])); else ret = max(ret, st.query_max(1, 1, n, dfn[y], dfn[x])); return ret;}
int query_sum(int x, int y) { int ret = 0, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret += st.query_sum(1, 1, n, dfn[fx], dfn[x]), x = fa[fx]; else ret += st.query_sum(1, 1, n, dfn[fy], dfn[y]), y = fa[fy]; fx = top[x]; fy = top[y]; } if (dfn[x] < dfn[y]) ret += st.query_sum(1, 1, n, dfn[x], dfn[y]); else ret += st.query_sum(1, 1, n, dfn[y], dfn[x]); return ret; int ret = 0, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret += st.query_sum(1, 1, n, dfn[fx], dfn[x]), x = fa[fx]; else ret += st.query_sum(1, 1, n, dfn[fy], dfn[y]), y = fa[fy]; fx = top[x]; fy = top[y]; } if (dfn[x] < dfn[y]) ret += st.query_sum(1, 1, n, dfn[x], dfn[y]); else ret += st.query_sum(1, 1, n, dfn[y], dfn[x]); return ret;}
signed main() { ios::sync_with_stdio(0); cin.tie(), cout.tie(); cin >> n; for (int i = 1;i < n;i++) cin >> a >> b, add(a, b), add(b, a); for (int i = 1;i <= n;i++) cin >> w[i]; dep[1] = 1; dfs1(1); dfs2(1, 1); st.build(1, 1, n); cin >> q; while (q--) { cin >> op >> u >> v; if (strcmp(op, "CHANGE") == 0) st.update(1, 1, n, dfn[u], v); if (strcmp(op, "QMAX") == 0) cout << query_max(u, v) << endl; if (strcmp(op, "QSUM") == 0) cout << query_sum(u, v) << endl; } return 0; ios::sync_with_stdio(0); cin.tie(), cout.tie(); cin >> n; for (int i = 1;i < n;i++) cin >> a >> b, add(a, b), add(b, a); for (int i = 1;i <= n;i++) cin >> w[i]; dep[1] = 1; dfs1(1); dfs2(1, 1); st.build(1, 1, n); cin >> q; while (q--) { cin >> op >> u >> v; if (strcmp(op, "CHANGE") == 0) st.update(1, 1, n, dfn[u], v); if (strcmp(op, "QMAX") == 0) cout << query_max(u, v) << endl; if (strcmp(op, "QSUM") == 0) cout << query_sum(u, v) << endl; } return 0;}```## K-D Tree(KDT)> KDT:二维数点我是 $\mathcal{O}(n\sqrt{n})$,三维数点我是 $\mathcal{O}(n\sqrt{n})$,四维数点我还是 $\mathcal{O}(n\sqrt{n})$!毒瘤围困万千重,我自岿然不动!:::align{right}——[$\bf\sf\color{#fe4c61}{Wxb2010}$](https://www.luogu.com.cn/user/1415227 "博客园:https://www.cnblogs.com/HBoier")[$\,\bf\sf\small\colorbox{#fe4c61}{\color{white}{rp++}}$](https://help.luogu.com.cn/manual/luogu/account/user-tag):::# 离线算法## 普通莫队```cpp line-numbersint n, m, k, bl, l = 1, r = 0, ans, a[N], cnt[N], res[N];
struct S { int l, r, i;} b[N];
void add(int i) { ans -= cnt[a[i]] * cnt[a[i]]; cnt[a[i]]++; ans += cnt[a[i]] * cnt[a[i]];}
void del(int i) { ans -= cnt[a[i]] * cnt[a[i]]; cnt[a[i]]--; ans += cnt[a[i]] * cnt[a[i]];}
signed main() { cin >> n >> m >> k; bl = sqrt(n); for (int i = 1;i <= n;i++) cin >> a[i]; for (int i = 1;i <= m;i++) cin >> b[i].l >> b[i].r, b[i].i = i; sort(b + 1, b + 1 + m, [](S x, S y) { int bx = x.l / bl, by = y.l / bl; if (bx != by) return x.l < y.l; if (bx & 1) return x.r < y.r; return x.r > y.r; });
for (int i = 1;i <= m;i++) { while (l > b[i].l) add(--l); while (r < b[i].r) add(++r); while (l < b[i].l) del(l++); while (r > b[i].r) del(r--); res[b[i].i] = ans; } for (int i = 1;i <= m;i++) cout << res[i] << endl; return 0;}```## 带修莫队```cpp line-numbersint n, m, bl, l = 1, r = 0, t, cntq, cntm, ans, a[N], cnt[N], res[N];char op;
struct S { int l, r, i, t;} b[N], c[N];
void add(int i) { ans += !(cnt[a[i]]++);}
void del(int i) { ans -= !(--cnt[a[i]]);}
void update(int pos, int &val, int ql, int qr) { if (ql <= pos && pos <= qr) { del(pos); swap(a[pos], val); add(pos); } else swap(a[pos], val);}
signed main() { cin >> n >> m; bl = 2500; for (int i = 1;i <= n;i++) cin >> a[i]; for (int i = 1;i <= m;i++) { cin >> op; if (op == 'Q') { cntq++; cin >> b[cntq].l >> b[cntq].r; b[cntq].i = cntq; b[cntq].t = cntm; } else { cntm++; cin >> c[cntm].l >> c[cntm].r; // l:元素位置,r:替换的值 } } sort(b + 1, b + 1 + cntq, [](S x, S y) { int blx = x.l / bl, bly = y.l / bl, brx = x.r / bl, bry = y.r / bl; if (blx != bly) return x.l < y.l; if (brx != bry) return x.r < y.r; return x.t < y.t; });
for (int i = 1;i <= cntq;i++) { while (l > b[i].l) add(--l); while (r < b[i].r) add(++r); while (l < b[i].l) del(l++); while (r > b[i].r) del(r--); while (t > b[i].t) update(c[t].l, c[t].r, b[i].l, b[i].r), t--; while (t < b[i].t) ++t, update(c[t].l, c[t].r, b[i].l, b[i].r); res[b[i].i] = ans; } for (int i = 1;i <= cntq;i++) cout << res[i] << endl; return 0;}```## 回滚莫队(不删除莫队)```cpp line-numbersint n, m, bl, l = 1, r = 0, num, ans, lans, a[N], cnt[N], res[N];int val[N], t[N];vector <int> vis, upd;
struct S { int l, r, i;} b[N];
void add(int i, bool v) { ans = max(ans, val[a[i]] * (++cnt[a[i]])); if (v) vis.push_back(a[i]); else upd.push_back(a[i]);}
signed main() { cin >> n >> m; bl = sqrt(n); for (int i = 1;i <= n;i++) cin >> a[i], t[i] = a[i]; sort(t + 1, t + 1 + n); num = unique(t + 1, t + 1 + n) - t - 1; for (int i = 1;i <= n;i++) { a[i] = lower_bound(t + 1, t + 1 + num, a[i]) - t; val[a[i]] = t[a[i]]; } for (int i = 1;i <= m;i++) cin >> b[i].l >> b[i].r, b[i].i = i; sort(b + 1, b + 1 + m, [](S x, S y) { int bx = x.l / bl, by = y.l / bl; if (bx != by) return x.l < y.l; return x.r < y.r; });
for (int i = 1;i <= m;) { int bi = b[i].l / bl, R = min(n, (bi + 1) * bl); l = R + 1, r = R, ans = 0; for (int j = 0;j < upd.size();j++) cnt[upd[j]] = 0; upd = vector <int> (); for (;i <= m && b[i].l / bl == bi;i++) { vis = vector <int> (); if (b[i].r <= R) { lans = ans; for (int j = b[i].l;j <= b[i].r;j++) add(j, 1); res[b[i].i] = ans; ans = lans; for (int j = 0;j < vis.size();j++) cnt[vis[j]]--; continue; }
while (r < b[i].r) add(++r, 0); lans = ans; int L = l; while (l > b[i].l) add(--l, 1); res[b[i].i] = ans;
ans = lans; l = L; for (int j = 0;j < vis.size();j++) cnt[vis[j]]--; } } for (int i = 1;i <= m;i++) cout << res[i] << endl; return 0;}```# 杂项## `iconv.h` 头文件缺失```h/* Copyright (C) 1999-2019 Free Software Foundation, Inc.238 行未改动全部展开 #endif /* _LIBICONV_H */```## __gnu__pbds 哈希报错```cpp```cpp line-numbers#include <functional> // 需要导入的头文件```加在你的代码里(以下四选一)```cpp```cpp line-numbersnamespace std { namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { size_t h1 = std::hash <int> {} (p.first); size_t h2 = std::hash <int> {} (p.second); // Boost-like hash combine return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); } }; } namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { size_t h1 = std::hash <int> {} (p.first); size_t h2 = std::hash <int> {} (p.second); // Boost-like hash combine return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); } }; }}``````cpp```cpp line-numbersnamespace std { namespace tr1 { template <> struct hash <std::pair<int, int> > { size_t operator () (const std::pair <int, int>& p) const { const size_t prime = 0x9e3779b1; // 黄金比例质数 size_t hash = std::hash <int> {} (p.first); hash ^= std::hash <int> {} (p.second) + prime + (hash << 12) + (hash >> 4); return hash; } }; } namespace tr1 { template <> struct hash <std::pair<int, int> > { size_t operator () (const std::pair <int, int>& p) const { const size_t prime = 0x9e3779b1; // 黄金比例质数 size_t hash = std::hash <int> {} (p.first); hash ^= std::hash <int> {} (p.second) + prime + (hash << 12) + (hash >> 4); return hash; } }; }}``````cpp```cpp line-numbersnamespace std { namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { const size_t FNV_prime = 0x100000001b3; size_t hash = 0xcbf29ce484222325; // FNV_offset_basis // Hash first hash ^= static_cast <size_t> (p.first); hash *= FNV_prime; // Hash second hash ^= static_cast <size_t> (p.second); hash *= FNV_prime; return hash; } }; } namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { const size_t FNV_prime = 0x100000001b3; size_t hash = 0xcbf29ce484222325; // FNV_offset_basis // Hash first hash ^= static_cast <size_t> (p.first); hash *= FNV_prime; // Hash second hash ^= static_cast <size_t> (p.second); hash *= FNV_prime; return hash; } }; }}``````cpp```cpp line-numbersnamespace std { namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { // 将两个整数拼接为"first,second"的字符串形式后哈希 std::string s = std::to_string(p.first) + "," + std::to_string(p.second); return std::hash <std::string> {} (s); } }; } namespace tr1 { template <> struct hash <std::pair <int, int> > { size_t operator () (const std::pair <int, int>& p) const { // 将两个整数拼接为"first,second"的字符串形式后哈希 std::string s = std::to_string(p.first) + "," + std::to_string(p.second); return std::hash <std::string> {} (s); } }; }}```## C++ 随机数据生成器 `random.h`by cyx012113```h/*Please run by C++11 or higher version! Otherwise, it could not work!
Usage:1. Include this header file: #include "random.h"2. Call random number generation functions, such as _srandm, _irandm, etc., passing the required parameters to generate random numbers or random strings.
Header Functionality:This header provides a series of random number generation functions,including random number generators based on the Mersenne Twister algorithm and the default random number generator,as well as functions for generating random characters and strings.
Main Functional Functions:- _srandm, _irandm, _lrandm, etc.: Generate random numbers within a specified range- _srandd, _irandd, _lrandd, etc.: Generate random numbers using the default random engine- _srandr, _irandr, _lrandr, etc.: Generate random numbers using the rand() function- _srandm, _srandd, _srandr, etc.: Generate random strings
Other Notes:This header uses random number generators from the C++ standard library,and simplifies the use of data types through macro definitions.
Usage of Random Data Generator:Call the _gen_data function to generate data.
Parameter Description:- _make_data: A function pointer that points to the data generation function, which accepts an integer parameter (the ID of the current dataset).- _func: A function pointer that points to the function that processes the generated data, which takes no parameters.- _id: The number of datasets to generate.- _checker: A function pointer that point to the data checker function, this function should return true or false.- _left: [Optional] The starting value of the dataset ID, defaulting to 0.- _zip: [Optional] Add files to data.zip, defaulting to 0.- _clean_up: [Optional] After generate, delete data files (exclude .yml/.cpp), defaultint to 0.- _delete_in_out: [Optional] Before generate, delete *.in and *.out files.Defaulting to 0.- _inter/_spj/_config: [Optional] Add interactive_lib.cpp/checker.cpp/config.yml to zip (before use that, please open "_zip").Defaulting to 0.- _color: [Optional] Setting CMD color.Defaulting to "9f".
void _gen_data(void (*_make_data)(_i _now_id), void (*_func)(), _i _id, _i _left = 1, bool _zip = 0, bool _clean_up = 0, bool _ios = 0, bool _inter = 0, bool _spj = 0, bool _config = 0, _str _color = "9f")
Example:void make_data(int id) { // id represents the current data point number // Write logic here to determine the range of data corresponding to the current id // Write logic here to generate data}
void process_data() { // Write logic here to process the data // Paste you code here}
int main() { _gen_data(make_data, process_data, 10, 1, 1, 1); // Generate 10 datasets and process them, id from 1 to 10, then compress.Final, delete datas.}
Update Jan, 23th of 2025: Add "zip" function.Update Jan, 25th of 2025: Add "clean_up" function.Update Feb, 20th of 2025: Improve code readability and add comments.Add "rand_odd/rand_even/rand_prime" functions.Update Feb, 26th of 2025: Fix "get_prime", "_irandm_odd" functions.Update May, 10th of 2025: Add "checker" function.Update Aug, 5th of 2025: Improve _gen_data function, removed "_ios" option, added "_delete_in_out", added "clean data.zip".
Codeing by @cyx012113, Feb 8th of 2025.// =============================================================================*/
#include <bits/stdc++.h>#include <unistd.h>
#define _s short#define _i int#define _l long#define _ll long long#define _ull unsigned long long#define _f float#define _d double#define _c char#define _str stringusing namespace std;
const _ull inf = INT_MAX;default_random_engine _rand;
_ull _get_seed() { auto now = chrono::system_clock::now(); auto timestamp = chrono::duration_cast<chrono::nanoseconds>(now.time_since_epoch()); return static_cast <_ull> (timestamp.count());}
mt19937_64 _mt(_get_seed());vector <_ull> _prime;vector <bool> _ip;_ull _p = 0;
vector <_ull> _get_prime(_ull _max) { _max *= 200; _prime.clear(); _prime.resize(_max + 2); _ip.clear(); _ip.resize(_max + 2); _ip[0] = _ip[1] = 1; for (_ull _it = 2;_it <= _max;_it++) { if (!_ip[_it]) _prime[++_p] = _it; for (int j = 1;j <= _p && _it * _prime[j] <= _max;j++) { _ip[_it * _prime[j]] = 1; if (_it % _prime[j] == 0) break; } } return _prime;}
_ull _randm(_ull _mod) { _ull _t = 0; while (_t <= _mod) _t += _mt() % 2, _t <<= 1; return (_t % _mod + _mt() % 2) % _mod;}_s _srandm(_s _mod) {return _randm(_mod);}_s _srandm(_s _min, _s _max) {return _min + _srandm(_max - _min);}_i _irandm(_i _mod) {return _randm(_mod);}_i _irandm(_i _min, _i _max) {return _min + _irandm(_max - _min);}_l _lrandm(_l _mod) {return _randm(_mod);}_l _lrandm(_l _min, _l _max) {return _min + _lrandm(_max - _min);}_ll _llrandm(_ll _mod) {return _randm(_mod);}_ll _llrandm(_ll _min, _ll _max) {return _min + _llrandm(_max - _min);}_ull _ullrandm(_ull _mod) {return _randm(_mod);}_ull _ullrandm(_ull _min, _ull _max) {return _min + _ullrandm(_max - _min);}
_c _crandm(_str _st = "10000", _str _add = "") { _str _letter = "abcdefghijklmnopqrstuvwxyz"; _str _upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; _str _symbol = "`~!@#$%^&*()-_=+{}[]|\\:;\"'<>,.?/"; _str _number = "1234567890";## ANSI 转义 - 控制台颜色调整```cpp line-numbers// ANSI 颜色代码class Color {public: // 前景色 static const string BLACK; static const string RED; static const string GREEN; static const string YELLOW; static const string BLUE; static const string MAGENTA; static const string CYAN; static const string WHITE; static const string BRIGHT_BLACK; static const string BRIGHT_RED; static const string BRIGHT_GREEN; static const string BRIGHT_YELLOW; static const string BRIGHT_BLUE; static const string BRIGHT_MAGENTA; static const string BRIGHT_CYAN; static const string BRIGHT_WHITE; _str _all = _add; while (_st.size() < 5) _st += "0"; if (_st[0] == '1') _all += _letter; if (_st[1] == '1') _all += _upper; if (_st[2] == '1') _all += _symbol; if (_st[3] == '1') _all += _number; if (_st[4] == '1') _all += " "; // 背景色 static const string BG_BLACK; static const string BG_RED; static const string BG_GREEN; static const string BG_YELLOW; static const string BG_BLUE; static const string BG_MAGENTA; static const string BG_CYAN; static const string BG_WHITE; static const string BG_BRIGHT_BLACK; static const string BG_BRIGHT_RED; static const string BG_BRIGHT_GREEN; static const string BG_BRIGHT_YELLOW; static const string BG_BRIGHT_BLUE; static const string BG_BRIGHT_MAGENTA; static const string BG_BRIGHT_CYAN; static const string BG_BRIGHT_WHITE; // 重置 static const string RESET; // 组合颜色 static string fg_bg(const string& fg, const string& bg) { return _all[_mt() % _all.size()];} return fg + bg; }};
_str _strrandm(_ull _len, _str _st = "10000", _str _add = "") { _str _t; for (_i i = 1;i <= _len;i++) _t += _crandm(_st, _add); return _t;}// 定义颜色常量const string Color::BLACK = "\033[30m";const string Color::RED = "\033[31m";const string Color::GREEN = "\033[32m";const string Color::YELLOW = "\033[33m";const string Color::BLUE = "\033[34m";const string Color::MAGENTA = "\033[35m";const string Color::CYAN = "\033[36m";const string Color::WHITE = "\033[37m";
_str _strrandm(_ull _min, _ull _max, _str _st = "10000", _str _add = "") {return _strrandm(_ullrandm(_min, _max), _st, _add);}const string Color::BRIGHT_BLACK = "\033[90m";const string Color::BRIGHT_RED = "\033[91m";const string Color::BRIGHT_GREEN = "\033[92m";const string Color::BRIGHT_YELLOW = "\033[93m";const string Color::BRIGHT_BLUE = "\033[94m";const string Color::BRIGHT_MAGENTA = "\033[95m";const string Color::BRIGHT_CYAN = "\033[96m";const string Color::BRIGHT_WHITE = "\033[97m";
_ull _randm_odd(_i _mod) { _ull t = _ullrandm(_mod); if (t % 2 == 0 && t != 0) t--; else if (t == 0) t = 1; return t;}_s _srandm_odd(_i _mod) {return _randm_odd(_mod);}_s _srandm_odd(_s _min, _s _max) {return _min + _srandm_odd(_max - _min);}_i _irandm_odd(_i _mod) { return _randm_odd(_mod);}_i _irandm_odd(_i _min, _i _max) {return _min + _irandm_odd(_max - _min);}_l _lrandm_odd(_l _mod) {return _randm_odd(_mod);}_l _lrandm_odd(_l _min, _l _max) {return _min + _lrandm_odd(_max - _min);}_ll _llrandm_odd(_ll _mod) {return _randm_odd(_mod);}_ll _llrandm_odd(_ll _min, _ll _max) {return _min + _llrandm_odd(_max - _min);}_ull _ullrandm_odd(_ull _mod) {return _randm_odd(_mod);}_ull _ullrandm_odd(_ull _min, _ull _max) {return _min + _ullrandm_odd(_max - _min);}const string Color::BG_BLACK = "\033[40m";const string Color::BG_RED = "\033[41m";const string Color::BG_GREEN = "\033[42m";const string Color::BG_YELLOW = "\033[43m";const string Color::BG_BLUE = "\033[44m";const string Color::BG_MAGENTA = "\033[45m";const string Color::BG_CYAN = "\033[46m";const string Color::BG_WHITE = "\033[47m";
_ull _randm_even(_i _mod) { _ull t = _ullrandm(_mod); if (t % 2 == 1 && t != 0) t--; return t;}_s _srandm_even(_i _mod) {return _randm_even(_mod);}_s _srandm_even(_s _min, _s _max) {return _min + _srandm_even(_max - _min);}_i _irandm_even(_i _mod) {return _randm_even(_mod);}_i _irandm_even(_i _min, _i _max) {return _min + _irandm_even(_max - _min);}_l _lrandm_even(_l _mod) {return _randm_even(_mod);}_l _lrandm_even(_l _min, _l _max) {return _min + _lrandm_even(_max - _min);}_ll _llrandm_even(_ll _mod) {return _randm_even(_mod);}_ll _llrandm_even(_ll _min, _ll _max) {return _min + _llrandm_even(_max - _min);}_ull _ullrandm_even(_ull _mod) {return _randm_even(_mod);}_ull _ullrandm_even(_ull _min, _ull _max) {return _min + _ullrandm_even(_max - _min);}const string Color::BG_BRIGHT_BLACK = "\033[100m";const string Color::BG_BRIGHT_RED = "\033[101m";const string Color::BG_BRIGHT_GREEN = "\033[102m";const string Color::BG_BRIGHT_YELLOW = "\033[103m";const string Color::BG_BRIGHT_BLUE = "\033[104m";const string Color::BG_BRIGHT_MAGENTA = "\033[105m";const string Color::BG_BRIGHT_CYAN = "\033[106m";const string Color::BG_BRIGHT_WHITE = "\033[107m";
_ull _randm_prime(_i _mod) { if (_prime.size() < _mod) _prime = _get_prime(_mod); _ull _pos = _randm(_mod); return _prime[(_pos % _prime.size()) == 0 ? 1 : _pos];}_s _srandm_prime(_i _mod) {return _randm_prime(_mod);}_i _irandm_prime(_i _mod) {return _randm_prime(_mod);}_l _lrandm_prime(_l _mod) {return _randm_prime(_mod);}_ll _llrandm_prime(_ll _mod) {return _randm_prime(_mod);}_ull _ullrandm_prime(_ull _mod) {return _randm_prime(_mod);}const string Color::RESET = "\033[0m";
// Rand Default_Random_ull _randd(_s _mod) { _ull _t = 0; while (_t <= _mod) _t += _rand() % 2, _t <<= 1; return (_t % _mod + _rand() % 2) % _mod;}_s _srandd(_s _mod) {return _randd(_mod);}_s _srandd(_s _min, _s _max) {return _min + _srandd(_max - _min);}_i _irandd(_i _mod) {return _randd(_mod);}_i _irandd(_i _min, _i _max) {return _min + _irandd(_max - _min);}_l _lrandd(_l _mod) {return _randd(_mod);}_l _lrandd(_l _min, _l _max) {return _min + _lrandd(_max - _min);}_ll _llrandd(_ll _mod) {return _randd(_mod);}_ll _llrandd(_ll _min, _ll _max) {return _min + _llrandd(_max - _min);}_ull _ullrandd(_ull _mod) {return _randd(_mod);}_ull _ullrandd(_ull _min, _ull _max) {return _min + _ullrandd(_max - _min);}#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004#endif
_c _crandd(_str _st = "10000", _str _add = "") { _str _letter = "abcdefghijklmnopqrstuvwxyz"; _str _upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; _str _symbol = "`~!@#$%^&*()-_=+{}[]|\\:;\"'<>,.?/"; _str _number = "1234567890"; _str _all = _add; while (_st.size() < 5) _st += "0"; if (_st[0] == '1') _all += _letter; if (_st[1] == '1') _all += _upper; if (_st[2] == '1') _all += _symbol; if (_st[3] == '1') _all += _number; if (_st[4] == '1') _all += " "; return _all[_rand() % _all.size()];}
_str _strrandd(_ull _len, _str _st = "10000", _str _add = "") { _str _t; for (_i i = 1;i <= _len;i++) _t += _crandd(_st, _add); return _t;}_str _strrandd(_ull _min, _ull _max, _str _st = "10000", _str _add = "") {return _strrandd(_ullrandd(_min, _max), _st, _add);}
_ull _randd_odd(_ull _mod) { _ull _t = _randd(_mod); if (_t % 2 == 0 && _t != 0) _t--; else if (_t == 0) _t = 1; return _t;}_s _srandd_odd(_s _mod) {return _randd_odd(_mod);}_s _srandd_odd(_s _min, _s _max) {return _min + _srandd_odd(_max - _min);}_i _irandd_odd(_i _mod) {return _randd_odd(_mod);}_i _irandd_odd(_i _min, _i _max) {return _min + _irandd_odd(_max - _min);}_l _lrandd_odd(_l _mod) {return _randd_odd(_mod);}_l _lrandd_odd(_l _min, _l _max) {return _min + _lrandd_odd(_max - _min);}_ll _llrandd_odd(_ll _mod) {return _randd_odd(_mod);}_ll _llrandd_odd(_ll _min, _ll _max) {return _min + _llrandd_odd(_max - _min);}_ull _ullrandd_odd(_ull _mod) {return _randd_odd(_mod);}_ull _ullrandd_odd(_ull _min, _ull _max) {return _min + _ullrandd_odd(_max - _min);}
_ull _randd_even(_s _mod) { _ull _t = _ullrandd(_mod); if (_t % 2 == 1 && _t != 0) _t--; return _t;}_s _srandd_even(_s _mod) {return _randd_even(_mod);}_s _srandd_even(_s _min, _s _max) {return _min + _srandd_even(_max - _min);}_i _irandd_even(_i _mod) {return _randd_even(_mod);}_i _irandd_even(_i _min, _i _max) {return _min + _irandd_even(_max - _min);}_l _lrandd_even(_l _mod) {return _randd_even(_mod);}_l _lrandd_even(_l _min, _l _max) {return _min + _lrandd_even(_max - _min);}_ll _llrandd_even(_ll _mod) {return _randd_even(_mod);}_ll _llrandd_even(_ll _min, _ll _max) {return _min + _llrandd_even(_max - _min);}_ull _ullrandd_even(_ull _mod) {return _randd_even(_mod);}_ull _ullrandd_even(_ull _min, _ull _max) {return _min + _ullrandd_even(_max - _min);}
_ull _randd_prime(_s _mod) { if (_prime.size() < _mod) _prime = _get_prime(_mod); _ull _pos = _randd(_mod); return _prime[(_pos % _prime.size()) == 0 ? 1 : _pos];}_s _srandd_prime(_s _mod) {return _randd_prime(_mod);}_i _irandd_prime(_i _mod) {return _randd_prime(_mod);}_l _lrandd_prime(_l _mod) {return _randd_prime(_mod);}_ll _llrandd_prime(_ll _mod) {return _randd_prime(_mod);}_ull _ullrandd_prime(_ull _mod) {return _randd_prime(_mod);}
// Rand rand_ull _randr(_s _mod) { _ull _t = 0; while (_t <= _mod) _t += rand() % 2, _t <<= 1; return (_t % _mod + rand() % 2) % _mod;}_s _srandr(_s _mod) {return _randr(_mod);}_s _srandr(_s _min, _s _max) {return _min + _srandr(_max - _min);}_i _irandr(_i _mod) {return _randr(_mod);}_i _irandr(_i _min, _i _max) {return _min + _irandr(_max - _min);}_l _lrandr(_l _mod) {return _randr(_mod);}_l _lrandr(_l _min, _l _max) {return _min + _lrandr(_max - _min);}_ll _llrandr(_ll _mod) {return _randr(_mod);}_ll _llrandr(_ll _min, _ll _max) {return _min + _llrandr(_max - _min); }_ull _ullrandr(_ull _mod) {return _randr(_mod);}_ull _ullrandr(_ull _min, _ull _max) {return _min + _ullrandr(_max - _min);}
_c _crandr(_str _st = "10000", _str _add = "") { _str _letter = "abcdefghijklmnopqrstuvwxyz"; _str _upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; _str _symbol = "`~!@#$%^&*()-_=+{}[]|\\:;\"'<>,.?/"; _str _number = "1234567890"; _str _all = _add; while (_st.size() < 5) _st += "0"; if (_st[0] == '1') _all += _letter; if (_st[1] == '1') _all += _upper; if (_st[2] == '1') _all += _symbol; if (_st[3] == '1') _all += _number; if (_st[4] == '1') _all += " "; return _all[rand() % _all.size()];}
_str _strrandr(_ull _len, _str _st = "10000", _str _add = "") { _str _t; for (_i i = 1;i <= _len;i++) _t += _crandr(_st, _add); return _t;}
_str _strrandr(_ull _min, _ull _max, _str _st = "10000", _str _add = "") {return _strrandr(_ullrandr(_min, _max), _st, _add);}
_ull _randr_odd(_ull _mod) { _ull t = _randr(_mod); if (t % 2 == 0 && t != 0) t--; else if (t == 0) t = 1; return t;}_s _srandr_odd(_s _mod) {return _randr_odd(_mod);}_s _srandr_odd(_s _min, _s _max) {return _min + _srandr_odd(_max - _min);}_i _irandr_odd(_i _mod) {return _randr_odd(_mod);}_i _irandr_odd(_i _min, _i _max) {return _min + _irandr_odd(_max - _min);}_l _lrandr_odd(_l _mod) {return _randr_odd(_mod);}_l _lrandr_odd(_l _min, _l _max) {return _min + _lrandr_odd(_max - _min);}_ll _llrandr_odd(_ll _mod) {return _randr_odd(_mod);}_ll _llrandr_odd(_ll _min, _ll _max) {return _min + _llrandr_odd(_max - _min);}_ull _ullrandr_odd(_ull _mod) {return _randr_odd(_mod);}_ull _ullrandr_odd(_ull _min, _ull _max) {return _min + _ullrandr_odd(_max - _min);}
_ull _randr_even(_ull _mod) { _ull _t = _ullrandd(_mod); if (_t % 2 == 1 && _t != 0) _t--; return _t;}_s _srandr_even(_s _mod) {return _randr_even(_mod);}_s _srandr_even(_s _min, _s _max) {return _min + _srandr_even(_max - _min);}_i _irandr_even(_i _mod) {return _randr_even(_mod);}_i _irandr_even(_i _min, _i _max) {return _min + _irandr_even(_max - _min);}_l _lrandr_even(_l _mod) {return _randr_even(_mod);}_l _lrandr_even(_l _min, _l _max) {return _min + _lrandr_even(_max - _min);}_ll _llrandr_even(_ll _mod) {return _randr_even(_mod);}_ll _llrandr_even(_ll _min, _ll _max) {return _min + _llrandr_even(_max - _min);}_ull _ullrandr_even(_ull _mod) {return _randr_even(_mod);}_ull _ullrandr_even(_ull _min, _ull _max) {return _min + _ullrandr_even(_max - _min);}
_ull _randr_prime(_ull _mod) { if (_prime.size() < _mod) _prime = _get_prime(_mod); _ull _pos = _randr(_mod); return _prime[(_pos % _prime.size()) == 0 ? 1 : _pos];}_s _srandr_prime(_s _mod) {return _randr_prime(_mod);}_i _irandr_prime(_i _mod) {return _randr_prime(_mod);}_l _lrandr_prime(_l _mod) {return _randr_prime(_mod);}_ll _llrandr_prime(_ll _mod) {return _randr_prime(_mod);}_ull _ullrandr_prime(_ull _mod) {return _randr_prime(_mod);}
string _get_command(bool _is_update, string _path, string _name) { string _temp = "powershell Compress-Archive -Path " + _path + "\\" + _name; if (_is_update) _temp += " -Update"; _temp += " -DestinationPath " + _path + "\\data.zip"; return _temp;}
// Compress Data and Config Files void _push_to_zip(bool _inter = 0, bool _spj = 0, bool _config = 0) { _c _cwd[256]; getcwd(_cwd, 256); _str _path = _cwd; if (_path[_path.size() - 1] == '\\') _path.erase(_path.size() - 1); clog << "Now path: " << _path << "\n"; _d start = clock(); _str _command = _get_command(0, _path, "*.in"); clog << "Add *.in to zip...\nCommand: " << _command << "\n"; system(_command.c_str());bool EnableVTMode() { HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hOut == INVALID_HANDLE_VALUE) return false; _command = _get_command(1, _path, "*.out"); clog << "Add *.out to zip...\nCommand: " << _command << "\n"; system(_command.c_str()); DWORD dwMode = 0; if (!GetConsoleMode(hOut, &dwMode)) return false; if (_inter) { _command = _get_command(1, _path, "interactive_lib.cpp"); clog << "Add interactive_lib.cpp to zip...\nCommand: " << _command << "\n"; system(_command.c_str()); } if (_spj) { _command = _get_command(1, _path, "checker.cpp"); clog << "Add checker.cpp to zip...\nCommand: " << _command << "\n"; system(_command.c_str()); } if (_config) { _command = _get_command(1, _path, "config.yml"); clog << "Add config.yml to zip...\nCommand: " << _command << "\n"; system(_command.c_str()); } _d end = clock(); clog << "Finish, time: " << (end - start) / CLOCKS_PER_SEC << " sec\n"; dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; return SetConsoleMode(hOut, dwMode);}
bool _check_files(string _file_name) { _c _cwd[256]; getcwd(_cwd, 256); _str _path = _cwd; if (_path[_path.size() - 1] == '\\') _path.erase(_path.size() - 1); string _command = "powershell -command \"if (Test-Path \"" + _path + "\\" + _file_name + "\") {exit 0} else {exit 1}\"";class ScopedColor {private: ostream& os; clog << "Finding files, Command: " << _command << endl; _i _result = system(_command.c_str()); return _result == 0;}
void _clean() { _c _cwd[256]; getcwd(_cwd, 256); _str _path = _cwd; if (_path[_path.size() - 1] == '\\') _path.erase(_path.size() - 1); clog << "Cleaning...\nCommand: \n"; if (_check_files("*.in")) { _str _command1 = "powershell Remove-Item -path \"" + _path + "\"\\*.in"; clog << "\t" << _command1 << "\n"; system(_command1.c_str()); } if (_check_files("*.out")) { _str _command2 = "powershell Remove-Item -path \"" + _path + "\"\\*.out"; clog << "\t" << _command2 << "\n"; system(_command2.c_str()); }}
bool _gen_data(void (*_make_data)(_i _now_id), void (*_func)(), bool (*_checker)(), _i _id, _i _left = 1, bool _zip = 0, bool _clean_up = 1, bool _delete_in_out = 1, bool _inter = 0, bool _spj = 0, bool _config = 0, _str _color = "9f") { _d START = clock(); clog << "Getting ready to generate data...\n"; _color = "color " + _color; system(_color.c_str()); _c _cwd[256]; getcwd(_cwd, 256); _str _path = _cwd; if (_path[_path.size() - 1] == '\\') _path.erase(_path.size() - 1); if (_delete_in_out) { char _cwd[256]; getcwd(_cwd, 256); _str _path = _cwd; if (_path[_path.size() - 1] == '\\') _path.erase(_path.size() - 1); _str _command1 = "powershell Remove-Item -path \"" + _path + "\"\\*.in"; _str _command2 = "powershell Remove-Item -path \"" + _path + "\"\\*.out"; _str _command3 = "powershell Remove-Item -path \"" + _path + "\"\\data.zip"; clog << "Deleting files...\nCommand: \n\t" << _command1 << "\n\t" << _command2 << "\n\t" << _command3 << "\n"; if (_check_files("*.in")) system(_command1.c_str()); if (_check_files("*.out")) system(_command2.c_str()); if (_check_files("data.zip")) system(_command3.c_str()); } _rand.seed(_get_seed()); for (_i _it = _left;_it <= _id;_it++) { clog << "Data #" << _it << ": Generating\n"; _d start = clock(); char in[10], out[10]; sprintf(in, "%d.in", _it); sprintf(out, "%d.out", _it); freopen(in, "wb", stdout); cout << ""; _make_data(_it); fclose(stdout); _d _end = clock(), time1 = (_end - start) / CLOCKS_PER_SEC; clog << "Data #" << _it << ": Generate time " << time1 << " sec\n"; clog << "Data #" << _it << ": Running\n"; _d _start = clock(); freopen(in, "r", stdin); freopen(out, "wb", stdout); if (!_checker()) { clog << "Fail to check Data #" << _it << "\n"; _it--; continue; } cout << ""; _func(); fclose(stdin); fclose(stdout); _d end = clock(), time2 = (end - _start) / CLOCKS_PER_SEC, time3 = (end - start) / CLOCKS_PER_SEC; clog << "Data #" << _it << ": Run time " << time2 << " sec\n"; clog << "Data #" << _it << ": Finish, time " << time3 << " sec" << "\n";public: ScopedColor(ostream& stream, const string& colorCode) : os(stream) { os << colorCode; } if (_zip) _push_to_zip(_inter, _spj, _config); if (_clean_up) _clean(); _d END = clock(); clog << "\nAll time: "<< (END - START) / CLOCKS_PER_SEC << " sec\n"; return 1; ~ScopedColor() { os << "\033[0m"; // 自动重置 }};
if (!EnableVTMode()) { cout << "警告: 无法启用虚拟终端模式,颜色可能无法显示" << endl;}```## 对拍 bat```shell@echo offg++.exe -O3 -std=c++14 std.cpp -o std.exeg++.exe -O3 -std=c++14 test.cpp -o test.exeg++.exe -O3 -std=c++14 random.cpp -o random.exe:looprandom.exe > in.txtstd.exe < in.txt > std.txttest.exe < in.txt > out.txtfc std.txt out.txtif %errorlevel% == 0 goto looppause```# 更新日志> update 2024.3.15:> - 增加函数个数;> - 增加主函数模板(加强版);109 行未改动全部展开
> update 2025.8.22:> - 更新了线段树模板的单点修改和乘积查询。
> update 2026.2.10:> - 增加了扩展欧几里得(Exgcd)、中国剩余定理(CRT)、扩展中国剩余定理(ExCRT)模板。
> update 2026.8.7:> - 增加了普通莫队模板,删除了 `random.h`。
> update 2026.8.8:> - 增加了带修莫队、回滚莫队模板,新增了 Tips。
> update 2026.8.9:> - 增加了带修莫队和回滚莫队模板,增加了卡常 Tips,重新放置了部分模板,修复了代码的一些错误,删除了图论模板中部分无用内容。
[回到顶部](# "单击可回到顶部")