正文
增加 553 行删除 2156 行
12345678910111213141516171853 行未改动7273747576777879808135 行未改动11711811912012112212312412518 行未改动1441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791802 行未改动1831841851861871881891901918 行未改动20020120220320420520620720831 行未改动2402412422432442452462472483 行未改动2522532542552562572582592605 行未改动2662672682692702712722732743 行未改动2782792802812822832842852862872882892902912922932942952962972982993003013023033043 行未改动3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533545 行未改动3603613623633643653663673686 行未改动37537637737837938038138238321 行未改动40540640740840941041141241325 行未改动43944044144244344444544644749 行未改动4974984995005015025035045057 行未改动51351451551651751851952052189 行未改动61161261361461561661761861983 行未改动70370470570670770870971071171210 行未改动72372472572672772872973073110 行未改动74274374474574674774874975035 行未改动78678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592610 行未改动9379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218652 行未改动22392240224122422243224422452246224717 行未改动22652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230311 行未改动2315231623172318231923202321232223233 行未改动23272328232923302331233223332334233532 行未改动23682369237023712372237323742375237674 行未改动24512452245324542455245624572458245928 行未改动24882489249024912492249324942495249611 行未改动2508250925102511251225132514251525167 行未改动252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725587 行未改动2566256725682569257025712572257325742575257625772578257916 行未改动25962597259825992600260126022603260411 行未改动2616261726182619262026212622262326248 行未改动2633263426352636263726382639264026412642264310 行未改动265426552656265726582659266026612662266326642665266626672668266926708 行未改动2679268026812682268326842685268626872 行未改动269026912692269326942695269626972698269920 行未改动27202721272227232724272527262727272827292730273127322733273427352736273727382739274012 行未改动27532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277619 行未改动2796279727982799280028012802280328043 行未改动2808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628379 行未改动2847284828492850285128522853285428552856285728582859286035 行未改动289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292650 行未改动2977297829792980298129822983298429852986116 行未改动全部展开31033104310531063107310831093110311159 行未改动31713172317331743175317631773178317946 行未改动322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325017 行未改动32683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329119 行未改动33113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333423 行未改动33583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338138 行未改动342034213422342334243425342634273428342934305 行未改动34363437343834393440344134423443344422 行未改动3467346834693470347134723473347434753476347734784 行未改动348334843485348634873488348934903491553 行未改动全部展开404540464047404840494050405140524053366 行未改动全部展开44204421442244234424442544264427442860 行未改动4489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745187 行未改动4526452745284529453045314532453345345 行未改动4540454145424543454445454546454745483 行未改动4552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651497 行未改动全部展开514951505151515251535154515551565157321 行未改动全部展开547954805481548254835484548554865487109 行未改动全部展开559755985599560056015602560356045605143 行未改动全部展开574957505751575257535754575557565757325 行未改动全部展开60836084608560866087608860896090609117 行未改动610961106111611261136114611561166117118 行未改动全部展开62366237623862396240624162426243238 行未改动全部展开64826483648464856486648764886489649064916492649364946 行未改动6501650265036504650565066507650865096 行未改动65166517651865196520652165226523652414 行未改动6539654065416542654365446545654665475 行未改动65536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070246 行未改动全部展开73177318731973207321[](https://www.luogu.com.cn/article/xjmzumm3/edit "编辑:此操作仅作者有效") [](https://blog.csdn.net/cyx012113?type=blog "作者 CSDN") [](https://www.luogu.com.cn/user/1099138 "作者主页")# 预处理## 主函数模板```cpp#include <bits/stdc++.h>using namespace std;signed main() {return 0;}```## 主函数模板(加强版)```cpp#define _USE_MATH_DEFINES#include <bits/stdc++.h>#include <bits/extc++.h>//#define int long long53 行未改动return 0;}```## 指令集优化```cpp#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/AVX51235 行未改动#define SIMD_AVAILABLE 0#endif```## 编译设置(洛谷等 OJ 限制使用 `#pragma GCC optimize`)```cpp#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")18 行未改动#pragma GCC diagnostic ignored "-Wunused-variable"#pragma GCC diagnostic ignored "-Wsign-compare"```## 关闭同步流```cpp#include <fstream>ios::sync_with_stdio(0);cin.tie(0), cout.tie(0);```## 手写 Rand```cppunsigned 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());}mt19937_64 mt(get_seed());long long Rand(long long mod) {long long t = 0;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);}```# 数学操作## 判断质数```cppbool 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)```cppconst int test_time = 10;unsigned long long get_seed() {auto now = chrono::system_clock::now();8 行未改动while (t <= mod) t += mt() % 2, t <<= 1;return (t % mod + mt() % 2) % mod;}int qp(int a, int b, int mod) { // 快速幂int ans = 1;while (b) {if (b & 1) ans = (ans * a) % mod;b >>= 1;31 行未改动| 20 | $(4^{-20} \approx 9.09 \times 10^{-13}) (\approx 0.000000000091\%)$ | $\approx 100%$ |建议:不小于 $10$ 即可。## 输出因数```cppvoid of(int n) {if (n < 1) return;if (n == 1) {cout << "1" << endl;3 行未改动if (n % i == 0) cout << i << endl;}```## 分解质因数```cppvector <int> Gif(int n) {vector <int> result;for (int i = 2;i * i <= n;i++) {if (n % i == 0) {5 行未改动return result;}```## 倒转数```cppint rv(int n) {int t = 0;while (n > 0) {t *= 10;3 行未改动return t;}```## 阶乘```cppint fact(int n) {int ans = 1;for (int i = 2;i <= n;i++) ans *= i;return ans;}```## 排列组合```cppint C(int n, int m) {return fact(n) / fact(m) / fact(n - m);}int A(int n, int m) {return fact(n) / fact(n - m);}```## 快速幂```cppint qp(int a, int b, int mod) {int ans = 1;while (b) {if (b & 1) ans = (ans * a) % mod;3 行未改动return ans;}```## 龟速乘```cppint lm(int a, int b, int mod) {int ans = 1;while (b) {if (b & 1) ans = (ans + a) % mod;b >>= 1;a = (a + a) % mod;}}```## 快速乘```cppint qm(int a, int b, int mod) {int c = a * b - ((long double)a / mod * b + 0.5L) * mod;if (c < mod) return c;return c + mod;}```## 勾股定理```cppdouble pt(double a, double b) {return sqrt(pow(a, 2) + pow(b, 2));}```## 两点距离```cppdouble 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) {double p = (a + b + c) / 2;return sqrt(p * (p - a) * (p - b) * (p - c));}```## 线性逆元```cppint n, p, inv[N], factinv[N];signed main() {cin >> n >> p;5 行未改动return 0;}```## 扩展欧几里得(Exgcd)```cppint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;6 行未改动return r;}```## 中国剩余定理(CRT)```cppint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;21 行未改动cout << (s + ans) % ans << endl;```## 扩展中国剩余定理(ExCRT)```cppint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;25 行未改动}cout << (Y % X + X) % X << endl;```## 手写根号```cpp#define exp 0.000001// 二分法double binsearch_sqrt(int m) {49 行未改动return 1 / y;}```## 线性基```cppstruct LinearBase {int dat[N];void insert(int x) {for (int i = 63;~i;i--) {7 行未改动}} lb;```## 日期计算```cppstruct _time {int y, m, d, h, min, s;int mmod[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};89 行未改动}};```## Base 64 编码 / 解码```cpp#include <bits/stdc++.h>using namespace std;static const string base64_chars =83 行未改动cout << base64_encode(c, 64) << endl << base64_decode(s) << endl;return 0;}```## 欧拉(线性)筛质数```cppint pr[N];bool ip[N];int gp(int n) {10 行未改动return p;}```## 归并排序```cppint 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;10 行未改动for (int k = l;k <= r;k++) A[k] = B[k];}```## 矩阵快速幂 / 矩阵乘法```cpp#include <bits/stdc++.h>using namespace std;const ll N = 1e2 + 2, mod = 1e9 + 7;35 行未改动}return 0;}```## 高精度```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;}```## 快速位运算```cppint 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(高精度浮点数,未格式化)```cppusing 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 = 1000; // 默认精度(位数)// 规范化数字(移除前导/后缀零,调整指数)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) {}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;}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) {// 数字 >= 1for (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.1result += "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.0int 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和divisorint 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;}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);// 新增数学函数friend ext_double gcd(const ext_double &a, const ext_double &b);friend ext_double lcm(const ext_double &a, const ext_double &b);friend ext_double log(const ext_double &x);friend ext_double log2(const ext_double &x);friend ext_double log10(const ext_double &x);friend ext_double ln(const ext_double &x);friend ext_double exp(const ext_double &x);friend ext_double acos(const ext_double &x);friend ext_double acosh(const ext_double &x);friend ext_double asin(const ext_double &x);friend ext_double asinh(const ext_double &x);friend ext_double atan(const ext_double &x);friend ext_double atan2(const ext_double &y, const ext_double &x);friend ext_double atanh(const ext_double &x);friend ext_double copysign(const ext_double &x, const ext_double &y);friend ext_double cos(const ext_double &x);friend ext_double cosh(const ext_double &x);friend ext_double degrees(const ext_double &x);friend ext_double erf(const ext_double &x);friend ext_double erfc(const ext_double &x);friend ext_double expm1(const ext_double &x);friend ext_double factorial(const ext_double &x);friend ext_double hypot(const ext_double &x, const ext_double &y);friend ext_double radians(const ext_double &x);friend ext_double sin(const ext_double &x);friend ext_double sinh(const ext_double &x);friend ext_double tan(const ext_double &x);friend ext_double tanh(const ext_double &x);friend ext_double trunc(const ext_double &x);// 数学常量static ext_double pi();static ext_double e();static ext_double tau();};// 数学常量实现ext_double ext_double::pi() {// 使用高精度π值return ext_double("3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679");}ext_double ext_double::e() {// 使用高精度e值return ext_double("2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274");}ext_double ext_double::tau() {return pi() * ext_double(2);}// 数学函数实现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("1e-50");ext_double guess = x;int max_iterations = 100;int iterations = 0;while (iterations < max_iterations) {ext_double new_guess = (guess + x / guess) / ext_double(2);if (abs(new_guess - guess) < precision) return new_guess;guess = new_guess;iterations++;}return guess;}ext_double cbrt(const ext_double &x) {if (isnan(x)) return x;if (isinf(x)) return x;ext_double precision = ext_double("1e-50");ext_double guess = x;int max_iterations = 100;int iterations = 0;while (iterations < max_iterations) {ext_double new_guess = (ext_double(2) * guess + x / (guess * guess)) / ext_double(3);if (abs(new_guess - guess) < precision) return new_guess;guess = new_guess;iterations++;}return guess;}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))实现return exp(exponent * log(base));}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);}// 新增数学函数实现ext_double gcd(const ext_double &a, const ext_double &b) {if (isnan(a) || isnan(b) || isinf(a) || isinf(b)) return ext_double::quiet_NaN();if (a == ext_double(0) && b == ext_double(0)) return ext_double(0);ext_double x = abs(a);ext_double y = abs(b);while (y != ext_double(0)) {ext_double temp = y;y = x % y;x = temp;}return x;}ext_double lcm(const ext_double &a, const ext_double &b) {if (isnan(a) || isnan(b) || isinf(a) || isinf(b)) return ext_double::quiet_NaN();if (a == ext_double(0) || b == ext_double(0)) return ext_double(0);return abs(a * b) / gcd(a, b);}ext_double log(const ext_double &x) {if (isnan(x)) return x;if (x <= ext_double(0)) return ext_double::quiet_NaN();if (isinf(x)) return x;if (x == ext_double(1)) return ext_double(0);// 使用泰勒级数展开ext_double result = ext_double(0);ext_double term = (x - ext_double(1)) / (x + ext_double(1));ext_double term_sq = term * term;ext_double current_term = term;for (int i = 1; i <= 100; i++) {result = result + ext_double(2) * current_term / ext_double(2 * i - 1);current_term = current_term * term_sq;if (abs(current_term) < ext_double("1e-50")) break;}return result;}ext_double log10(const ext_double &x) {return log(x) / log(ext_double(10));}ext_double log2(const ext_double &x) {return log(x) / log(ext_double(2));}ext_double ln(const ext_double &x) {return log(x);}ext_double exp(const ext_double &x) {if (isnan(x)) return x;if (isinf(x)) {if (x > ext_double(0)) return ext_double::infinity();else return ext_double(0);}// 使用泰勒级数展开ext_double result = ext_double(1);ext_double term = ext_double(1);for (int i = 1; i <= 100; i++) {term = term * x / ext_double(i);result = result + term;if (abs(term) < ext_double("1e-50")) break;}return result;}ext_double sin(const ext_double &x) {if (isnan(x)) return x;if (isinf(x)) return ext_double::quiet_NaN();// 使用泰勒级数展开ext_double result = ext_double(0);ext_double term = x;ext_double x_sq = x * x;for (int i = 1; i <= 100; i++) {result = result + term;term = term * x_sq / ext_double(-(2 * i) * (2 * i + 1));if (abs(term) < ext_double("1e-50")) break;}return result;}ext_double cos(const ext_double &x) {if (isnan(x)) return x;if (isinf(x)) return ext_double::quiet_NaN();// 使用泰勒级数展开ext_double result = ext_double(1);ext_double term = ext_double(1);ext_double x_sq = x * x;for (int i = 1; i <= 100; i++) {term = term * x_sq / ext_double(-(2 * i - 1) * (2 * i));result = result + term;if (abs(term) < ext_double("1e-50")) break;}return result;}ext_double tan(const ext_double &x) {return sin(x) / cos(x);}ext_double asin(const ext_double &x) {if (isnan(x)) return x;if (x < ext_double(-1) || x > ext_double(1)) return ext_double::quiet_NaN();// 使用泰勒级数展开ext_double result = x;ext_double term = x;ext_double x_sq = x * x;for (int i = 1; i <= 100; i++) {term = term * x_sq * ext_double(2 * i - 1) * ext_double(2 * i - 1) / ext_double(2 * i) / ext_double(2 * i + 1);result = result + term;if (abs(term) < ext_double("1e-50")) break;}return result;}ext_double acos(const ext_double &x) {return ext_double::pi() / ext_double(2) - asin(x);}ext_double atan(const ext_double &x) {if (isnan(x)) return x;if (isinf(x)) return (x > ext_double(0)) ? ext_double::pi() / ext_double(2) : -ext_double::pi() / ext_double(2);// 使用泰勒级数展开if (abs(x) <= ext_double(1)) {ext_double result = x;ext_double term = x;ext_double x_sq = x * x;for (int i = 1; i <= 100; i++) {term = term * x_sq * ext_double(-1) * ext_double(2 * i - 1) / ext_double(2 * i + 1);result = result + term;if (abs(term) < ext_double("1e-50")) break;}return result;} else {return (x > ext_double(0) ? ext_double::pi() / ext_double(2) : -ext_double::pi() / ext_double(2)) - atan(ext_double(1) / x);}}ext_double atan2(const ext_double &y, const ext_double &x) {if (isnan(x) || isnan(y)) return ext_double::quiet_NaN();if (x == ext_double(0) && y == ext_double(0)) return ext_double(0);ext_double result = atan(y / x);if (x < ext_double(0)) {if (y >= ext_double(0)) result = result + ext_double::pi();else result = result - ext_double::pi();}return result;}ext_double sinh(const ext_double &x) {return (exp(x) - exp(-x)) / ext_double(2);}ext_double cosh(const ext_double &x) {return (exp(x) + exp(-x)) / ext_double(2);}ext_double tanh(const ext_double &x) {return sinh(x) / cosh(x);}ext_double asinh(const ext_double &x) {return log(x + sqrt(x * x + ext_double(1)));}ext_double acosh(const ext_double &x) {if (x < ext_double(1)) return ext_double::quiet_NaN();return log(x + sqrt(x * x - ext_double(1)));}ext_double atanh(const ext_double &x) {if (x <= ext_double(-1) || x >= ext_double(1)) return ext_double::quiet_NaN();return log((ext_double(1) + x) / (ext_double(1) - x)) / ext_double(2);}ext_double hypot(const ext_double &x, const ext_double &y) {return sqrt(x * x + y * y);}ext_double copysign(const ext_double &x, const ext_double &y) {ext_double result = abs(x);result.sign = y.sign;return result;}ext_double degrees(const ext_double &x) {return x * ext_double(180) / ext_double::pi();}ext_double radians(const ext_double &x) {return x * ext_double::pi() / ext_double(180);}ext_double erf(const ext_double &x) {// 误差函数近似实现ext_double result = ext_double(0);ext_double term = x;ext_double x_sq = x * x;for (int i = 0; i < 100; i++) {ext_double denominator = ext_double(2 * i + 1);for (int j = 1; j <= i; j++) {denominator = denominator * ext_double(-j);}term = term * x_sq / denominator;result = result + term;if (abs(term) < ext_double("1e-50")) break;}return result * ext_double(2) / sqrt(ext_double::pi());}ext_double erfc(const ext_double &x) {return ext_double(1) - erf(x);}ext_double expm1(const ext_double &x) {return exp(x) - ext_double(1);}ext_double factorial(const ext_double &x) {if (isnan(x) || x < ext_double(0) || floor(x) != x) return ext_double::quiet_NaN();if (isinf(x)) return ext_double::infinity();ext_double result = ext_double(1);for (ext_double i = ext_double(2); i <= x; i = i + ext_double(1)) {result = result * i;}return result;}ext_double trunc(const ext_double &x) {if (isnan(x) || isinf(x)) return x;return (x >= ext_double(0)) ? floor(x) : ceil(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 << "gcd(12, 18) = " << gcd(ext_double(12), ext_double(18)) << endl;cout << "lcm(12, 18) = " << lcm(ext_double(12), ext_double(18)) << endl;cout << "log(100) = " << log(ext_double(100)) << endl;cout << "log10(1000) = " << log10(ext_double(1000)) << endl;cout << "sin(π/2) = " << sin(ext_double::pi() / 2) << endl;cout << "cos(π) = " << cos(ext_double::pi()) << endl;cout << "tan(π/4) = " << tan(ext_double::pi() / 4) << endl;cout << "infinity: " << ext_double::infinity() << endl;cout << "NaN: " << ext_double::quiet_NaN() << endl;cout << "π = " << ext_double::pi() << endl;cout << "e = " << ext_double::e() << endl;cout << "τ = " << ext_double::tau() << endl;return 0;}```## 快速傅里叶变换 / 逆变换(FFT / IFFT)```cppstruct Complex {double x, y;Complex(double _x = 0.0, double _y = 0.0) {52 行未改动if (on == -1) for (int i = 0;i < len;i++) y[i].x /= len, y[i].y /= len;}```## 快速数论变换(NTT)```cppvoid ntt(int *x, int lim, int opt) {int k, gn, g, tmp;for (int i = 0; i < lim; ++i)17 行未改动for (int i = 0;i < lim;i++) x[i] = 1ll * x[i] * inv % P;}}```# 输入输出优化## 快读板子```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();}return x * f;}```## 快写板子```cppinline void print(int x) { // 快写if (x < 0) {putchar('-');x = -x;}if (x > 9) print(x / 10);putchar(x % 10 + '0');}```# 字符串操作## 树的遍历```cppvoid pre(int x) {cout << x << " ";if (a[x][1]) pre(a[x][1]);if (a[x][2]) pre(a[x][2]);11 行未改动cout << x << " ";}```## 判断回文字符串```cppbool 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 字典树```cppint trie[N][MN];int tot, sum[N];void insert(string s) { //插入一个字符串s32 行未改动sum[root] -= fa;}```## AC 自动机```cppnamespace AC {struct S {int son[27], ans, fail, du, id;void init() {74 行未改动return 0;}```## 回文自动机(PAM)```cppstruct Palindrome_Automaton {int ch[N][LN], fail[N], len[N], sum[N], cnt, last;Palindrome_Automaton() {cnt = 1;28 行未改动return 0;}```## Manacher 最长回文串```cppstring s = "~|";char c;int p[N], ans, r = 0, mid = 0;11 行未改动return 0;}```## 手写字符串 hash```cppconst ull M = 1610612741, P = 131;ull h[2000005];7 行未改动hash <string> _hash;```## 双模数 hash```cppconst ull mod1 = 1610612741, mod2 = 402653189, p = 131;struct s {ull x, y;bool operator < (const s & a) const {return a.x == x ? a.y < y : a.x < x;}bool operator > (const s & a) const {return a.x == x ? a.y > y : a.x > x;}}h[maxn];inline 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 ans = 0;for (int i = 1;i <= s.size();i++) ans = (ans * base + s[i]) % mod2;return ans;}```## 字符串任意子段 hash```cppull h[N], p[N];void init_Hash(string s) {int n = s.size();7 行未改动return h[pos + len] - h[pos] * p[len];}```## hash 质数表```cppull 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```cppvector <int> prefix(string s) {int n = s.size();vector <int> pi(n);for (int i = 1;i < n;i++) {16 行未改动}```# 图论算法## SPFA 最短路```cppint 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]++;while (!q.empty()) {int u = q.front();q.pop();8 行未改动if (!vis[v]) {q.push(v);vis[v] = true;cnt_in_queue[v]++;if (cnt_in_queue[v] > n) return true;}}}}10 行未改动add(a, b, c);}bool circle = spfa(s, n);if (circle) cout << "Graph contains a negative weight cycle!" << endl;return 0;}```## SPFA 优化版(SLF + LLL + 随机化)```cppint dis[N];int h[N], to[N], val[N], nxt[N], cnt, n, m, s, t, x, y, z;int cnt_in_queue[N];bool vis[N];void add(int a, int b, int c) {to[++cnt] = b;8 行未改动deque <int> q;q.push_back(s);vis[s] = true;cnt_in_queue[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) {q.push_back(u);u = q.front();q.pop_front();}20 行未改动vis[v] = true;sum += dis[v];q_size++;cnt_in_queue[v]++;if (cnt_in_queue[v] > n) return true;}else sum += dis[v];}}}return false;}```## SPFA Hack 数据生成器```cppunsigned 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());12 行未改动}void generate_hack_data() {const int n = 50000; // 节点数const int m = 500000; // 边数cout << n << " " << m << endl;// 1. 构造主链(权值为1的边)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) {int u = rng() % n + 1;int v = rng() % n + 1;if(u == v) v = v % n + 1; // 避免自环// 随机决定是添加反向边还是随机边if(rng() % 3 == 0 && u > 1) {// 添加高权值反向边(针对SLF优化)19 行未改动return 0;}```## Bellman-Ford 最短路```cppstruct 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;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 (!updated) break;}for (const 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;}}return true;}9 行未改动}bool circle = bellman_ford(s, n);if (!circle) cout << "Graph contains a negative weight cycle!" << endl;return 0;}```## Dijkstra 最短路```cppint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z, s, t;bool vis[N];struct node {35 行未改动}}signed main() {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 最短路```cppint 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]);}memset(dp, 0x7f, sizeof(dp));```## 最小生成树(Prim)```cppint dis[N], h[N], to[N], val[N], nxt[N], ans, cnt, n, m;bool vis[N];struct node {50 行未改动cout << ans << endl;return 0;}```## 最小生成树(Kruskal)```cppstruct Edge {int u, v, w;bool operator < (const Edge& other) const {return w < other.w;116 行未改动全部展开return 0;}```## Dinic 网络最大流```cppint 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 二分图匹配```cppint 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 割边 / 割点```cppint 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];17 行未改动if (flag >= 2 && u == root) cut_v[u] = 1;}```## tarjan 强连通分量```cppint 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];19 行未改动}}```## 拓扑排序```cppint 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];23 行未改动return topoOrder;}```## 最近公共祖先(LCA)```cppint 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];38 行未改动x = f[x][j], y = f[y][j];return f[x][0];}```# 小型数据结构## 并查集```cppint f[N];int find(int x) {if (f[x] == x) return x;5 行未改动if (fx != fy) f[fx] = fy;}```## ST 表```cpp#include <iostream>using namespace std;const int N = 2e5 + 2, Logn = 22;22 行未改动}```# 树形数据结构## 树状数组```cppint s[N];inline 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;}```## 线段树(指针版)```cppint n, m, mod = inf;int a[N];struct Segment_Tree {553 行未改动全部展开return 0;}```## 线段树(数组版)```cppint n, m, mod = inf;int a[N];struct Segment_Tree {366 行未改动全部展开return 0;}```## 线段树(加法版)```cppint n, m, mod;int a[N];struct Segment_Tree {60 行未改动return val;}```## 线段树(最小值版)```cppstruct Segment_Tree {int add;int min_val;int l, r;} s[N << 2];inline 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) {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) {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) {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) {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[N << 2];int n;vector <int> b;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);}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 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);}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;}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);}}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);}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);}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);}}};```## 可持久化线段树(主席树)- 指针版```cppint n, m, mod = inf;int a[N];vector <int> sorted; // 用于离散化的排序数组497 行未改动全部展开return 0;}```## 可持久化线段树(主席树)- 数组版```cppint n, m, mod = inf;int a[N];vector <int> sorted; // 离散化数组321 行未改动全部展开return 0;}```## Treap```cppint na;int ch[N][2];int val[N], dat[N];int sz[N], cnt[N];109 行未改动全部展开}```## Splay 伸展树from oi-wiki```cppint n, id, rt;int fa[N], val[N], cnt[N], sz[N], ch[N][2];bool dir(int x) {143 行未改动全部展开return 0;}```## 树套树(线段树套 Splay)```cpp// Splay Tree Node Structurestruct SplayNode {int val, cnt, sz;SplayNode *ch[2], *fa;325 行未改动全部展开return 0;}```## 笛卡尔树```cppint p[N], l[N], r[N], n;void build(int n) {stack <int> stk;17 行未改动return 0;}```## 树链剖分```cpp#define lc o << 1#define rc o << 1 | 1int n, a, b, w[N], q, u, v;118 行未改动全部展开}return 0;}```# 杂项## `iconv.h` 头文件缺失```h/* Copyright (C) 1999-2019 Free Software Foundation, Inc.238 行未改动全部展开#endif /* _LIBICONV_H */```## __gnu__pbds 哈希报错```cpp#include <functional> // 需要导入的头文件```加在你的代码里(以下四选一)```cppnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {6 行未改动};}}``````cppnamespace std {namespace tr1 {template <>struct hash <std::pair<int, int> > {6 行未改动};}}``````cppnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {14 行未改动};}}``````cppnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {5 行未改动};}}```## 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 stringsOther 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";_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[_mt() % _all.size()];}_str _strrandm(_ull _len, _str _st = "10000", _str _add = "") {_str _t;for (_i i = 1;i <= _len;i++) _t += _crandm(_st, _add);return _t;}_str _strrandm(_ull _min, _ull _max, _str _st = "10000", _str _add = "") {return _strrandm(_ullrandm(_min, _max), _st, _add);}_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);}_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);}_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);}// 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);}_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 Filesvoid _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());_command = _get_command(1, _path, "*.out");clog << "Add *.out to zip...\nCommand: " << _command << "\n";system(_command.c_str());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";}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}\"";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";}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;}```## ANSI 转义 - 控制台颜色调整```cpp// ANSI 颜色代码class Color {public:// 前景色246 行未改动全部展开> update 2026.2.10:> - 增加了扩展欧几里得(Exgcd)、中国剩余定理(CRT)、扩展中国剩余定理(ExCRT)模板。[回到顶部](# "单击可回到顶部")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939453 行未改动14814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820935 行未改动24524624724824925025125225318 行未改动2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083092 行未改动3123133143153163173183193208 行未改动32933033133233333433533633731 行未改动3693703713723733743753763773 行未改动3813823833843853863873883895 行未改动3953963973983994004014024033 行未改动4074084094104114124134144154164174184194204214224234244254264274284294304314324333 行未改动4374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824835 行未改动4894904914924934944954964976 行未改动50450550650750850951051151221 行未改动53453553653753853954054154225 行未改动56856957057157257357457557649 行未改动6266276286296306316326336347 行未改动64264364464564664764864965089 行未改动74074174274374474574674774883 行未改动83283383483583683783883984084110 行未改动85285385485585685785885986010 行未改动87187287387487587687787887935 行未改动91591691791891992092192292392410 行未改动93593693793893994094194294394452 行未改动99799899910001001100210031004100517 行未改动1023102410251026102710281029103010311032103311 行未改动1045104610471048104910501051105210533 行未改动10571058105910601061106210631064106532 行未改动10981099110011011102110311041105110674 行未改动11811182118311841185118611871188118928 行未改动12181219122012211222122312241225122611 行未改动12381239124012411242124312441245124612477 行未改动125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812897 行未改动1297129812991300130113021303130413051306130713081309131016 行未改动13271328132913301331133213331334133511 行未改动1347134813491350135113521353135413558 行未改动1364136513661367136813691370137113721373137410 行未改动13851386138713881389139013911392139313941395139613971398139914008 行未改动1409141014111412141314141415141614172 行未改动1420142114221423142414251426142714281429143020 行未改动14511452145314541455145614571458145914601461146214631464146514661467146814691470147112 行未改动14841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150719 行未改动1527152815291530153115321533153415353 行未改动15391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215639 行未改动1573157415751576157715781579158015811582158315841585158635 行未改动162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165250 行未改动1703170417051706170717081709171017111712116 行未改动全部展开18291830183118321833183418351836183759 行未改动18971898189919001901190219031904190546 行未改动19521953195419551956195719581959196019611962196319641965196617 行未改动1984198519861987198819891990199119921993199419951996199719 行未改动20172018201920202021202220232024202520262027202823 行未改动20522053205420552056205720582059206020612062206320642065206638 行未改动21052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621475 行未改动21532154215521562157215821592160216122 行未改动2184218521862187218821892190219121922193219421954 行未改动220022012202220322042205220622072208553 行未改动全部展开276227632764276527662767276827692770366 行未改动全部展开31373138313931403141314231433144314560 行未改动3206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432357 行未改动3243324432453246324732483249325032515 行未改动3257325832593260326132623263326432653 行未改动3269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359497 行未改动全部展开385738583859386038613862386338643865321 行未改动全部展开418741884189419041914192419341944195109 行未改动全部展开430543064307430843094310431143124313143 行未改动全部展开445744584459446044614462446344644465325 行未改动全部展开47914792479347944795479647974798479917 行未改动481748184819482048214822482348244825118 行未改动全部展开4944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139238 行未改动全部展开53785379538053815382538353845385538653875388538953906 行未改动5397539853995400540154025403540454056 行未改动54125413541454155416541754185419542014 行未改动5435543654375438543954405441544254435 行未改动5449545054515452545354545455545654575458246 行未改动全部展开57055706570757085709571057115712571357145715571657175718**注意:文章内容量较大,网页内存占用可能达到数 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 line-numbers#include <bits/stdc++.h>using namespace std;signed main() {return 0;}```## 主函数模板(加强版)```cpp line-numbers#define _USE_MATH_DEFINES#include <bits/stdc++.h>#include <bits/extc++.h>//#define int long long53 行未改动return 0;}```# 卡常## 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 line-numbersvoid print(int x) { // 快写if (x < 0) {putchar('-');x = -x;}if (x > 9) print(x / 10);putchar(x % 10 + '0');}```## 指令集优化```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/AVX51235 行未改动#define SIMD_AVAILABLE 0#endif```## 编译设置(洛谷等 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")18 行未改动#pragma GCC diagnostic ignored "-Wunused-variable"#pragma GCC diagnostic ignored "-Wsign-compare"```## 关闭同步流```cpp line-numbers#include <fstream>ios::sync_with_stdio(0);cin.tie(0), cout.tie(0);```# 数学操作## 随机数```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());}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;return (t % mod + mt() % 2) % mod;}long long Rand(long long l, long long r) {return l + Rand(r - l);}```## 判断质数```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 line-numbersconst int test_time = 10;unsigned long long get_seed() {auto now = chrono::system_clock::now();8 行未改动while (t <= mod) t += mt() % 2, t <<= 1;return (t % mod + mt() % 2) % mod;}int qp(int a, int b, int mod) {int ans = 1;while (b) {if (b & 1) ans = (ans * a) % mod;b >>= 1;31 行未改动| 20 | $(4^{-20} \approx 9.09 \times 10^{-13}) (\approx 0.000000000091\%)$ | $\approx 100%$ |建议:不小于 $10$ 即可。## 输出因数```cpp line-numbersvoid of(int n) {if (n < 1) return;if (n == 1) {cout << "1" << endl;3 行未改动if (n % i == 0) cout << i << endl;}```## 分解质因数```cpp line-numbersvector <int> Gif(int n) {vector <int> result;for (int i = 2;i * i <= n;i++) {if (n % i == 0) {5 行未改动return result;}```## 倒转数```cpp line-numbersint rv(int n) {int t = 0;while (n > 0) {t *= 10;3 行未改动return t;}```## 阶乘```cpp line-numbersint fact(int n) {int ans = 1;for (int i = 2;i <= n;i++) ans *= i;return ans;}```## 排列组合```cpp line-numbersint C(int n, int m) {return fact(n) / fact(m) / fact(n - m);}int A(int n, int m) {return fact(n) / fact(n - m);}```## 快速幂```cpp line-numbersint qp(int a, int b, int mod) {int ans = 1;while (b) {if (b & 1) ans = (ans * a) % mod;3 行未改动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;}```## 勾股定理```cpp line-numbersdouble pt(double a, double b) {return sqrt(pow(a, 2) + pow(b, 2));}```## 两点距离```cpp line-numbersdouble dist(double a1, double a2, double b1, double b2) {return sqrt(pow(fabs(a1 - b1), 2) + pow(fabs(a2 - b2), 2));}```## 海伦-秦九韶公式```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 line-numbersint n, p, inv[N], factinv[N];signed main() {cin >> n >> p;5 行未改动return 0;}```## 扩展欧几里得(Exgcd)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;6 行未改动return r;}```## 中国剩余定理(CRT)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;21 行未改动cout << (s + ans) % ans << endl;```## 扩展中国剩余定理(ExCRT)```cpp line-numbersint exgcd(int a, int b, int &x, int &y) {if (!b) {x = 1;y = 0;25 行未改动}cout << (Y % X + X) % X << endl;```## 手写根号```cpp line-numbers#define exp 0.000001// 二分法double binsearch_sqrt(int m) {49 行未改动return 1 / y;}```## 线性基```cpp line-numbersstruct LinearBase {int dat[N];void insert(int x) {for (int i = 63;~i;i--) {7 行未改动}} lb;```## 日期计算```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};89 行未改动}};```## Base 64 编码 / 解码```cpp line-numbers#include <bits/stdc++.h>using namespace std;static const string base64_chars =83 行未改动cout << base64_encode(c, 64) << endl << base64_decode(s) << endl;return 0;}```## 欧拉(线性)质数筛```cpp line-numbersint pr[N];bool ip[N];int gp(int n) {10 行未改动return p;}```## 归并排序```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;10 行未改动for (int k = l;k <= r;k++) A[k] = B[k];}```## 矩阵快速幂 / 矩阵乘法```cpp line-numbers#include <bits/stdc++.h>using namespace std;const ll N = 1e2 + 2, mod = 1e9 + 7;35 行未改动}return 0;}```## 快速位运算```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;}```## 快速傅里叶变换(FFT / IFFT)```cpp line-numbersstruct Complex {double x, y;Complex(double _x = 0.0, double _y = 0.0) {52 行未改动if (on == -1) for (int i = 0;i < len;i++) y[i].x /= len, y[i].y /= len;}```## 快速数论变换(NTT)```cpp line-numbersvoid ntt(int *x, int lim, int opt) {int k, gn, g, tmp;for (int i = 0; i < lim; ++i)17 行未改动for (int i = 0;i < lim;i++) x[i] = 1ll * x[i] * inv % P;}}```# 字符串操作## 树的遍历```cpp line-numbersvoid pre(int x) {cout << x << " ";if (a[x][1]) pre(a[x][1]);if (a[x][2]) pre(a[x][2]);11 行未改动cout << x << " ";}```## 判断回文字符串```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 line-numbersint trie[N][MN];int tot, sum[N];void insert(string s) { //插入一个字符串s32 行未改动sum[root] -= fa;}```## AC 自动机```cpp line-numbersnamespace AC {struct S {int son[27], ans, fail, du, id;void init() {74 行未改动return 0;}```## 回文自动机(PAM)```cpp line-numbersstruct Palindrome_Automaton {int ch[N][LN], fail[N], len[N], sum[N], cnt, last;Palindrome_Automaton() {cnt = 1;28 行未改动return 0;}```## Manacher 最长回文串```cpp line-numbersstring s = "~|";char c;int p[N], ans, r = 0, mid = 0;11 行未改动return 0;}```## 手写字符串 hash**热知识**:一定要用自己的模数,常用模数和自然溢出被卡遍了。```cpp line-numbersconst ull M = 1610612741, P = 131;ull h[2000005];7 行未改动hash <string> _hash;```## 双模数 hash```cpp line-numbersconst ull mod1 = 1610612741, mod2 = 402653189, p = 131;struct s {ull x, y;bool operator < (s a) const {return a.x == x ? a.y < y : a.x < x;}bool operator > (s a) const {return a.x == x ? a.y > y : a.x > x;}} h[maxn];ull hash1(string s) {ull ans = 0;for (int i = 1;i <= s.size();i++) ans = (ans * p + s[i]) % mod1;return ans;}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 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 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 line-numbersvector <int> prefix(string s) {int n = s.size();vector <int> pi(n);for (int i = 1;i < n;i++) {16 行未改动}```# 图论算法## SPFA 最短路```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;tot[s]++;while (!q.empty()) {int u = q.front();q.pop();8 行未改动if (!vis[v]) {q.push(v);vis[v] = true;tot[v]++;if (tot[v] > n) return true;}}}}10 行未改动add(a, b, c);}bool circle = spfa(s, n);if (!circle) ;// 处理负环return 0;}```## SPFA 优化版(SLF + LLL + 随机化)```cpp line-numbersint dis[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;8 行未改动deque <int> q;q.push_back(s);vis[s] = true;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();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++;tot[v]++;if (tot[v] > n) return true;}else sum += dis[v];}}}return false;}```## SPFA Hack 数据生成器```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());12 行未改动}void generate_hack_data() {int n = 50000; // 节点数int m = 500000; // 边数cout << n << " " << m << endl;// 1. 构造主链(权值为1的边)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++) {int u = rng() % n + 1;int v = rng() % n + 1;if (u == v) v = v % n + 1; // 避免自环// 随机决定是添加反向边还是随机边if(rng() % 3 == 0 && u > 1) {// 添加高权值反向边(针对SLF优化)19 行未改动return 0;}```## Bellman-Ford 最短路```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 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, f = true;}if (!f) break;}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;}return true;}9 行未改动}bool circle = bellman_ford(s, n);if (!circle) ;// 处理负环return 0;}```## Dijkstra 最短路```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 {35 行未改动}}signed main() {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 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]);}memset(dp, 0x3f, sizeof(dp));```## Prim 最小生成树```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], ans, cnt, n, m;bool vis[N];struct node {50 行未改动cout << ans << endl;return 0;}```## Kruskal 最小生成树```cpp line-numbersstruct Edge {int u, v, w;bool operator < (const Edge& other) const {return w < other.w;116 行未改动全部展开return 0;}```## Dinic 网络最大流```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 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 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];void add(int a, int b, int c) {to[++cnt] = b;val[cnt] = c;nxt[cnt] = h[a];17 行未改动if (flag >= 2 && u == root) cut_v[u] = 1;}```## tarjan 强连通分量```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;void add(int a, int b, int c) {to[++cnt] = b;val[cnt] = c;nxt[cnt] = h[a];19 行未改动}}```## 拓扑排序```cpp line-numbersint dis[N], h[N], to[N], val[N], nxt[N], cnt, n, m, x, y, z;int in[N];void add(int a, int b, int c) {to[++cnt] = b;val[cnt] = c;nxt[cnt] = h[a];23 行未改动return topoOrder;}```## 最近公共祖先(LCA)### 倍增法```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;void add(int a, int b, int c) {to[++cnt] = b;val[cnt] = c;nxt[cnt] = h[a];38 行未改动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 line-numbersint f[N];int find(int x) {if (f[x] == x) return x;5 行未改动if (fx != fy) f[fx] = fy;}```## ST 表```cpp line-numbers#include <iostream>using namespace std;const int N = 2e5 + 2, Logn = 22;22 行未改动}```# 树形数据结构## 树状数组```cpp line-numbersint s[N];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 line-numbersint n, m, mod = inf;int a[N];struct Segment_Tree {553 行未改动全部展开return 0;}```## 线段树(数组版)```cpp line-numbersint n, m, mod = inf;int a[N];struct Segment_Tree {366 行未改动全部展开return 0;}```## 线段树(加法版)```cpp line-numbersint n, m, mod;int a[N];struct Segment_Tree {60 行未改动return val;}```## 线段树(最小值版)```cpp line-numbersstruct Segment_Tree {int add;int min_val;int l, r;} s[N << 2];void pushup(int pos) {s[pos].min_val = min(s[pos << 1].min_val, s[pos << 1 | 1].min_val);}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;}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);}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);}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 线段树```cpp line-numbersint n, b[N];struct Segment_Tree {int sum;int g;} s[N << 2];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 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);}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);elseupdate(pos << 1 | 1, mid + 1, r, index, delta);pushup(pos);}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;}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 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);}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 line-numbersint n, m, mod = inf;int a[N];vector <int> sorted; // 用于离散化的排序数组497 行未改动全部展开return 0;}```## 可持久化线段树(主席树)- 数组版```cpp line-numbersint n, m, mod = inf;int a[N];vector <int> sorted; // 离散化数组321 行未改动全部展开return 0;}```## Treap```cpp line-numbersint na;int ch[N][2];int val[N], dat[N];int sz[N], cnt[N];109 行未改动全部展开}```## Splay 伸展树from oi-wiki```cpp line-numbersint n, id, rt;int fa[N], val[N], cnt[N], sz[N], ch[N][2];bool dir(int x) {143 行未改动全部展开return 0;}```## 树套树(线段树套 Splay)```cpp line-numbers// Splay Tree Node Structurestruct SplayNode {int val, cnt, sz;SplayNode *ch[2], *fa;325 行未改动全部展开return 0;}```## 笛卡尔树```cpp line-numbersint p[N], l[N], r[N], n;void build(int n) {stack <int> stk;17 行未改动return 0;}```## 树链剖分```cpp line-numbers#define lc o << 1#define rc o << 1 | 1int n, a, b, w[N], q, u, v;118 行未改动全部展开}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 line-numbers#include <functional> // 需要导入的头文件```加在你的代码里(以下四选一)```cpp line-numbersnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {6 行未改动};}}``````cpp line-numbersnamespace std {namespace tr1 {template <>struct hash <std::pair<int, int> > {6 行未改动};}}``````cpp line-numbersnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {14 行未改动};}}``````cpp line-numbersnamespace std {namespace tr1 {template <>struct hash <std::pair <int, int> > {5 行未改动};}}```## ANSI 转义 - 控制台颜色调整```cpp line-numbers// ANSI 颜色代码class Color {public:// 前景色246 行未改动全部展开> update 2026.2.10:> - 增加了扩展欧几里得(Exgcd)、中国剩余定理(CRT)、扩展中国剩余定理(ExCRT)模板。> update 2026.8.7:> - 增加了普通莫队模板,删除了 `random.h`。> update 2026.8.8:> - 增加了带修莫队、回滚莫队模板,新增了 Tips。> update 2026.8.9:> - 增加了带修莫队和回滚莫队模板,增加了卡常 Tips,重新放置了部分模板,修复了代码的一些错误,删除了图论模板中部分无用内容。[回到顶部](# "单击可回到顶部")