标题
增加 1 行删除 1 行
1负边权的小玩具1军火库说是
正文
增加 2737 行删除 31 行
1234567891046 行未改动57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105主要是自用。需要的可以自取。:::info[缺省源(6.31KB)]自带 `freopen`,计时器,随机数生成器,`c++17` 基数排序和 `gcd`。```cpp#include<bits/stdc++.h>#include<immintrin.h>#pragma GCC target("avx2")#include<ext/pb_ds/assoc_container.hpp>#include<ext/pb_ds/tree_policy.hpp>46 行未改动#define putchar(x) ((p3==ob+BS&&(fwrite(ob,p3-ob,1,stdout),p3=ob),*p3++=x))#endif#define isd(c) (c>47&&c<58)#define iss(c) (c<33)#define cin io#define cout iotemplate<typename T>inline bool read(T&s){s=0;int w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))s=s*10+c-48,c=getchar();return s*=w,1;}inline bool read(char&s){while(s=getchar(),iss(s));return s!=EOF;}inline bool read(char*s){char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))*s++=c,c=getchar();return *s=0,1;}inline bool read(std::string&s){s="";char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))s+=c,c=getchar();return 1;}template<typename T>inline bool read_f(T&x){x=0;T w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))x=x*10+(c^48),c=getchar();if(c=='.'){T f=0,k=1;while(c=getchar(),isd(c))f=f*10+(c^48),k*=10;x+=f/k;}x*=w;return 1;}inline bool read(float&x){return read_f(x);}inline bool read(double&x){return read_f(x);}inline bool read(long double&x){return read_f(x);}template<size_t N>inline bool read(std::bitset<N>&b){b.reset();char c;while(c=getchar(),c!='0'&&c!='1'&&c!=EOF);if(c==EOF)return 0;static char buf[N+5];int i=0;do{buf[i++]=c;c=getchar();}while((c=='0'||c=='1')&&i<N);For(j,0,i-1)if(buf[j]=='1')b[i-1-j]=1;return 1;}template<typename T>inline void write(T x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+48);}inline void write(char x){putchar(x);}inline void write(char*x){while(*x)putchar(*x++);}inline void write(const char*x){for(int i=0;x[i];i++)putchar(x[i]);}inline void write(std::string x){for(char c:x)putchar(c);}template<typename T>inline void write(T x,int k){if(x<0)putchar('-'),x=-x;T e=0.5;For(i,1,k)e/=10;x+=e;ull n=(ull)x;write(n);if(k>0){putchar('.');x-=n;For(i,1,k){x*=10;int c=(int)x;putchar(c+48);x-=c;}}}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(float x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(long double x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(double x){write(x,6);}template<size_t N>inline void write(std::bitset<N>b){write(b.to_string());}struct F{bool s=1;inline void flush(){fwrite(ob,p3-ob,1,stdout);p3=ob;}~F(){flush();}explicit operator bool()const{return s;}}io;template<typename T>inline F&operator>>(F&i,T&b){i.s=read(b);return i;}template<typename T>inline F&operator<<(F&i,T b){write(b);return i;}}using namespace fast_IO;template<typename T> using Set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;template<typename T,typename TT> using Map=gp_hash_table<T,TT>;void freopen(string name="test",int type=1,string aaa="",string bbb=""){if(type==1){freopen((name+".in").c_str(),"r",stdin),freopen((name+".out").c_str(),"w",stdout);}else if(type==2){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"w",stdout);}else if(type==3){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"wb",stdout);}else if(type==4){freopen((name+aaa).c_str(),"wb",stdout);}else{return;}}class Timer{private:ull GetCycleCount(){unsigned hi,lo;__asm__ volatile("rdtsc":"=a"(lo),"=d"(hi));return ((ull)(hi)<<32)|lo;}ull startCycle,startTime;public:void restart(){startCycle=GetCycleCount();startTime=chrono::steady_clock::now().time_since_epoch().count();}ull getCycles(){return GetCycleCount()-startCycle;}double getTime(){return (chrono::steady_clock::now().time_since_epoch().count()-startTime)/1e6;}}timer;class FastRand{private:ull s[4];ull rotl(const ull x,int k){return(x<<k)|(x>>(64-k));}ull next(){const ull res=rotl(s[0]+s[3],23)+s[0];const ull t=s[1]<<17;s[2]^=s[0];s[3]^=s[1];s[1]^=s[2];s[0]^=s[3];s[2]^=t;s[3]=rotl(s[3],45);return res;}public:FastRand(){mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());For(i,0,3)s[i]=rng();}int randint(int l,int r){ull range=(ull)r-l+1,v;if(range==0)return next();ull mask=(1ULL<<(64-__builtin_clzll(range-1)))-1;while((v=(next()&mask))>=range);return v+l;}double frand(double l,double r){const ull x=next();const union {ull i;double d;}u={.i=0x3FF0000000000000ULL|(x>>12)};return (u.d-1.0)*(r-l)+l;}}Rand;ll gcd(ll aa,ll bb){ll a=aa,b=bb;if(!a||!b)return a|b;ll shift=__builtin_ctzll(a|b);a>>=__builtin_ctzll(a);while(b){b>>=__builtin_ctzll(b);if(a>b)swap(a,b);b-=a;}return a<<shift;}Int gcd(Int aa,Int bb){Int a=aa,b=bb;if(!a||!b)return a|b;Int shift=__builtin_ctz(a|b);a>>=__builtin_ctz(a);while(b){b>>=__builtin_ctz(b);if(a>b)swap(a,b);b-=a;}return a<<shift;}constexpr Int N=5e5+5,MOD=998244353;#if __cplusplus > 201703Lnamespace Radix{int c[65536];template<typename T>void run(T* a,int n){static T t[N];T *x=a,*y=t,m=(T)1<<(sizeof(T)*8-1);For(i,0,n-1)x[i]^=m;for(int p=0;p<(int)sizeof(T)*8;p+=16){ms(c);For(i,0,n-1)c[(x[i]>>p)&0xFFFF]++;For(i,1,65535)c[i]+=c[i-1];Fro(i,n-1,0)y[--c[(x[i]>>p)&0xFFFF]]=x[i];swap(x,y);}if(x!=a)For(i,0,n-1)a[i]=x[i];For(i,0,n-1)a[i]^=m;}}template<typename T,typename Cmp=std::less<T>>void Sort(T* st,T* ed,Cmp cmp=Cmp()){int n=ed-st;if(n<2)Happy;if(n<131072||!is_integral_v<T>||!is_same_v<Cmp,std::less<T>>){sort(st,ed,cmp);Happy;}Radix::run(st,n);}#endifInt main(){timer.restart();Happy Ending;}```::::::info[快读]支持读入和输出指定位数的 `float`、`double`、`long double`,所有整数,`bitset`和`string`。使用 `cin` 和 `cout` 进行输入输出,有 `bool` 返回值。若开启 `-DONLINE_JUDGE` 在控制台输入样例后要 `CTRL_Z`。```cppnamespace fast_IO{const int BS=1<<20;char ib[BS],ob[BS],*p1=ib,*p2=ib,*p3=ob;#ifdef ONLINE_JUDGE#define getchar() ((p1==p2&&(p2=(p1=ib)+fread(ib,1,BS,stdin),p1==p2)?EOF:*p1++))#define putchar(x) ((p3==ob+BS&&(fwrite(ob,p3-ob,1,stdout),p3=ob),*p3++=x))#endif#define isd(c) (c>47&&c<58)#define iss(c) (c<33)#define cin io#define cout iotemplate<typename T>inline bool read(T&s){s=0;int w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))s=s*10+c-48,c=getchar();return s*=w,1;}inline bool read(char&s){while(s=getchar(),iss(s));return s!=EOF;}inline bool read(char*s){char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))*s++=c,c=getchar();return *s=0,1;}inline bool read(std::string&s){s="";char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))s+=c,c=getchar();return 1;}template<typename T>inline bool read_f(T&x){x=0;T w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))x=x*10+(c^48),c=getchar();if(c=='.'){T f=0,k=1;while(c=getchar(),isd(c))f=f*10+(c^48),k*=10;x+=f/k;}x*=w;return 1;}inline bool read(float&x){return read_f(x);}inline bool read(double&x){return read_f(x);}inline bool read(long double&x){return read_f(x);}template<size_t N>inline bool read(std::bitset<N>&b){b.reset();char c;while(c=getchar(),c!='0'&&c!='1'&&c!=EOF);if(c==EOF)return 0;static char buf[N+5];int i=0;do{buf[i++]=c;c=getchar();}while((c=='0'||c=='1')&&i<N);For(j,0,i-1)if(buf[j]=='1')b[i-1-j]=1;return 1;}template<typename T>inline void write(T x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+48);}inline void write(char x){putchar(x);}inline void write(char*x){while(*x)putchar(*x++);}inline void write(const char*x){for(int i=0;x[i];i++)putchar(x[i]);}inline void write(std::string x){for(char c:x)putchar(c);}template<typename T>inline void write(T x,int k){if(x<0)putchar('-'),x=-x;T e=0.5;For(i,1,k)e/=10;x+=e;ull n=(ull)x;write(n);if(k>0){putchar('.');x-=n;For(i,1,k){x*=10;int c=(int)x;putchar(c+48);x-=c;}}}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(float x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(long double x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(double x){write(x,6);}template<size_t N>inline void write(std::bitset<N>b){write(b.to_string());}struct F{bool s=1;inline void flush(){fwrite(ob,p3-ob,1,stdout);p3=ob;}~F(){flush();}explicit operator bool()const{return s;}}io;template<typename T>inline F&operator>>(F&i,T&b){i.s=read(b);return i;}template<typename T>inline F&operator<<(F&i,T b){write(b);return i;}}using namespace fast_IO;```::::::info[随机数生成器]在随机范围内随机生成若干个数时,效率大约为 `mt19937` 的1.5倍,且绝对均匀。```cppclass FastRand{private:ull s[4];ull rotl(const ull x,int k){return(x<<k)|(x>>(64-k));}ull next(){const ull res=rotl(s[0]+s[3],23)+s[0];const ull t=s[1]<<17;s[2]^=s[0];s[3]^=s[1];s[1]^=s[2];s[0]^=s[3];s[2]^=t;s[3]=rotl(s[3],45);return res;}public:FastRand(){mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());For(i,0,3)s[i]=rng();}int randint(int l,int r){ull range=(ull)r-l+1,v;if(range==0)return next();ull mask=(1ULL<<(64-__builtin_clzll(range-1)))-1;while((v=(next()&mask))>=range);return v+l;}double frand(double l,double r){const ull x=next();const union {ull i;double d;}u={.i=0x3FF0000000000000ULL|(x>>12)};return (u.d-1.0)*(r-l)+l;}}Rand;```:::1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267846 行未改动272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811主要是自用。需要的可以自取。::::success[缺省源]:::info[编译选项]```-std=c++26 -Wall -Wextra -Wl,-stack=536870912 -Wshadow -O2 -static```::::::info[交互题编译选项]```g++ grader.cpp [your_implemention] -o [your_implemention] -std=c++26 -Wall -Wextra -Wl,-stack=536870912 -Wshadow -O2 -static```::::::info[缺省源]```cpp#include<bits/stdc++.h>#include<ext/pb_ds/assoc_container.hpp>#include<ext/pb_ds/tree_policy.hpp>#include<ext/pb_ds/hash_policy.hpp>#include<ext/pb_ds/trie_policy.hpp>#include<ext/pb_ds/list_update_policy.hpp>#include<ext/pb_ds/priority_queue.hpp>#include<ext/rope>#define For(a,b,c) for(int a=(int)b;a<=(int)(c);a++)#define Fro(a,b,c) for(int a=(int)b;a>=(int)(c);a--)#define Fov(e,g) for(auto e:g)#define ms(a) memset(a,0,sizeof (a))#define msinf(a) memset(a,0x3f,sizeof (a))#define mss(a,b) memset(a,b,sizeof (a))#define mcp(a,b) memcpy(a,b,sizeof (a))#define fill(a,n,k) fill(a+1,a+1+n,k)#define fil(v,k) fill(v.begin(),v.end(),k)#define Pii pair<int,int>#define Inline __inline__#define ppc __builtin_popcount#define ctz __builtin_ctz#define fi first#define se second#define y1 y1ovo#define y2 y2ovo#define j1 j1ovo#define j2 j2ovo#define mkp make_pair#define pb push_back#define Int signed#define uint unsigned#define ll long long#define ull unsigned long long#define lll __int128#define ulll __uint128_t#define lld long double#define stdpq std::priority_queue#define Fopen(in) freopen(in".in","r",stdin);freopen(in".out","w",stdout);#ifndef ONLINE_JUDGE#define Ending return cerr<<"\nTime Used: "<<fixed<<setprecision(0)<<clock()<<" ms",0#else#define Ending return 0#endif#define LL#ifdef LL#define int long long#define inf 0x3f3f3f3f3f3f3f3f#else#define inf 0x3f3f3f3f#endifusing namespace std;using namespace __gnu_pbds;using namespace __gnu_cxx;namespace fast_IO{constexpr int BITSIZE=1<<16;char inBuffer[BITSIZE],outBuffer[BITSIZE],*startPtr=inBuffer,*endPtr=inBuffer,*outPtr=outBuffer;#ifdef ONLINE_JUDGE#define getchar() ((startPtr==endPtr&&(endPtr=(startPtr=inBuffer)+fread(inBuffer,1,BITSIZE,stdin),startPtr==endPtr)?EOF:*startPtr++))#endif#define putchar(x) ((outPtr==outBuffer+BITSIZE&&(fwrite(outBuffer,outPtr-outBuffer,1,stdout),outPtr=outBuffer),*outPtr++=x))#define cin io#define cout io#define Happy cout.flush();void read(){}void write(){}template<typename T>bool read(T&s){s=0;int w=1;char c;while(c=getchar(),!isdigit(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isdigit(c))s=s*10+c-48,c=getchar();return s*=w,1;}bool read(char&s){while(s=getchar(),isspace(s));return s!=EOF;}bool read(char*s){char c;while(c=getchar(),isspace(c));if(c==EOF)return 0;while(!isspace(c)&&c!=EOF)*s++=c,c=getchar();return *s=0,1;}bool read(std::string&s){s="";char c;while(c=getchar(),isspace(c));if(c==EOF)return 0;while(!isspace(c)&&c!=EOF)s+=c,c=getchar();return 1;}template<typename T>bool read_f(T&x){x=0;T w=1;char c;while(c=getchar(),!isdigit(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isdigit(c))x=x*10+(c^48),c=getchar();if(c=='.'){T f=0,k=1;while(c=getchar(),isdigit(c))f=f*10+(c^48),k*=10;x+=f/k;}x*=w;return 1;}bool read(float&x){return read_f(x);}bool read(double&x){return read_f(x);}bool read(long double&x){return read_f(x);}template<size_t N>bool read(std::bitset<N>&b){b.reset();char c;while(c=getchar(),c!='0'&&c!='1'&&c!=EOF);if(c==EOF)return 0;static char buf[N+5];int i=0;do{buf[i++]=c;c=getchar();}while((c=='0'||c=='1')&&i<N);for(int j=0;j<=i-1;j++)if(buf[j]=='1')b[i-1-j]=1;return 1;}template<typename T>void write(T x){if(x<0)putchar('-'),x=-x;static char st[45];int tp=0;do st[++tp]=x%10+48,x/=10;while(x);while(tp)putchar(st[tp--]);}void write(char x){putchar(x);}void write(char*x){int l=strlen(x);for(int i=0;i<l;i++)putchar(x[i]);}void write(const char*x){int l=strlen(x);for(int i=0;i<l;i++)putchar(x[i]);}void write(std::string x){for(char c:x)putchar(c);}template<typename T>void writef(T x,int k){if(x<0)putchar('-'),x=-x;x+=0.5*pow(10,-k);ull n=x;write(n);if(k>0){putchar('.');x-=n;For(i,1,k){x*=10;int c=(int)x;putchar(c+48);x-=c;}}}[[deprecated]]void write(float x){writef(x,6);} [[deprecated]]void write(long double x){writef(x,6);} [[deprecated]]void write(double x){writef(x,6);}template<size_t N>void write(std::bitset<N>b){write(b.to_string());}template<typename T,typename ...Tp>void write(T x,Tp ...y){write(x),write(y...);}template<typename T,typename ...Tp>void read(T &x,Tp &...y){read(x),read(y...);}struct FstIO{bool s=1;void flush(){fwrite(outBuffer,outPtr-outBuffer,1,stdout);outPtr=outBuffer;}~FstIO(){flush();}explicit operator bool()const{return s;}}io;template<typename T>FstIO&operator>>(FstIO&i,T&b){i.s=read(b);return i;}template<typename T>FstIO&operator<<(FstIO&i,T b){write(b);return i;}}using namespace fast_IO;void freopen(string name="test",int type=1,string aaa="",string bbb=""){if(type==1){freopen((name+".in").c_str(),"r",stdin),freopen((name+".out").c_str(),"w",stdout);}else if(type==2){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"w",stdout);}else if(type==3){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"wb",stdout);}else if(type==4){freopen((name+aaa).c_str(),"wb",stdout);}else{return;}}class FastRand{private:ull s[4];ull rotl(const ull x,int k){return(x<<k)|(x>>(64-k));}ull next(){const ull res=rotl(s[0]+s[3],23)+s[0];const ull t=s[1]<<17;s[2]^=s[0];s[3]^=s[1];s[1]^=s[2];s[0]^=s[3];s[2]^=t;s[3]=rotl(s[3],45);return res;}public:FastRand(){mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());For(i,0,3)s[i]=rng();}int randint(int l,int r){ull range=(ull)r-l+1,v;if(range==0)return next();ull mask=(1ULL<<(64-__builtin_clzll(range-1)))-1;while((v=(next()&mask))>=range);return v+l;}double frand(double l,double r){const union {ull i;double d;}u={.i=0x3FF0000000000000ULL|(next()>>12)};return (u.d-1.0)*(r-l)+l;}}Rand;constexpr int N=1e5+5,MOD=998244353;Int main(){Happy Ending;}```::::::info[除掉主函数的缺省源]```cpp#include<bits/stdc++.h>#include<ext/pb_ds/assoc_container.hpp>#include<ext/pb_ds/tree_policy.hpp>#include<ext/pb_ds/hash_policy.hpp>#include<ext/pb_ds/trie_policy.hpp>#include<ext/pb_ds/list_update_policy.hpp>#include<ext/pb_ds/priority_queue.hpp>#include<ext/rope>#define For(a,b,c) for(int a=(int)b;a<=(int)(c);a++)#define Fro(a,b,c) for(int a=(int)b;a>=(int)(c);a--)#define Fov(e,g) for(auto e:g)#define ms(a) memset(a,0,sizeof (a))#define msinf(a) memset(a,0x3f,sizeof (a))#define mss(a,b) memset(a,b,sizeof (a))#define mcp(a,b) memcpy(a,b,sizeof (a))#define fill(a,n,k) fill(a+1,a+1+n,k)#define fil(v,k) fill(v.begin(),v.end(),k)#define Pii pair<int,int>#define Inline __inline__#define ppc __builtin_popcount#define ctz __builtin_ctz#define fi first#define se second#define y1 y1ovo#define y2 y2ovo#define j1 j1ovo#define j2 j2ovo#define mkp make_pair#define pb push_back#define Int signed#define uint unsigned#define ll long long#define ull unsigned long long#define lll __int128#define ulll __uint128_t#define lld long double#define stdpq std::priority_queue#define Fopen(in) freopen(in".in","r",stdin);freopen(in".out","w",stdout);#ifndef ONLINE_JUDGE#define Ending return cerr<<"\nTime Used: "<<fixed<<setprecision(0)<<clock()<<" ms",0#else#define Ending return 0#endif#define LL#ifdef LL#define int long long#define inf 0x3f3f3f3f3f3f3f3f#else#define inf 0x3f3f3f3f#endifusing namespace std;using namespace __gnu_pbds;using namespace __gnu_cxx;namespace fast_IO{constexpr int BITSIZE=1<<16;char inBuffer[BITSIZE],outBuffer[BITSIZE],*startPtr=inBuffer,*endPtr=inBuffer,*outPtr=outBuffer;#ifdef ONLINE_JUDGE#define getchar() ((startPtr==endPtr&&(endPtr=(startPtr=inBuffer)+fread(inBuffer,1,BITSIZE,stdin),startPtr==endPtr)?EOF:*startPtr++))#endif#define putchar(x) ((outPtr==outBuffer+BITSIZE&&(fwrite(outBuffer,outPtr-outBuffer,1,stdout),outPtr=outBuffer),*outPtr++=x))#define cin io#define cout io#define Happy cout.flush();void read(){}void write(){}template<typename T>bool read(T&s){s=0;int w=1;char c;while(c=getchar(),!isdigit(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isdigit(c))s=s*10+c-48,c=getchar();return s*=w,1;}bool read(char&s){while(s=getchar(),isspace(s));return s!=EOF;}bool read(char*s){char c;while(c=getchar(),isspace(c));if(c==EOF)return 0;while(!isspace(c)&&c!=EOF)*s++=c,c=getchar();return *s=0,1;}bool read(std::string&s){s="";char c;while(c=getchar(),isspace(c));if(c==EOF)return 0;while(!isspace(c)&&c!=EOF)s+=c,c=getchar();return 1;}template<typename T>bool read_f(T&x){x=0;T w=1;char c;while(c=getchar(),!isdigit(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isdigit(c))x=x*10+(c^48),c=getchar();if(c=='.'){T f=0,k=1;while(c=getchar(),isdigit(c))f=f*10+(c^48),k*=10;x+=f/k;}x*=w;return 1;}bool read(float&x){return read_f(x);}bool read(double&x){return read_f(x);}bool read(long double&x){return read_f(x);}template<size_t N>bool read(std::bitset<N>&b){b.reset();char c;while(c=getchar(),c!='0'&&c!='1'&&c!=EOF);if(c==EOF)return 0;static char buf[N+5];int i=0;do{buf[i++]=c;c=getchar();}while((c=='0'||c=='1')&&i<N);for(int j=0;j<=i-1;j++)if(buf[j]=='1')b[i-1-j]=1;return 1;}template<typename T>void write(T x){if(x<0)putchar('-'),x=-x;static char st[45];int tp=0;do st[++tp]=x%10+48,x/=10;while(x);while(tp)putchar(st[tp--]);}void write(char x){putchar(x);}void write(char*x){int l=strlen(x);for(int i=0;i<l;i++)putchar(x[i]);}void write(const char*x){int l=strlen(x);for(int i=0;i<l;i++)putchar(x[i]);}void write(std::string x){for(char c:x)putchar(c);}template<typename T>void writef(T x,int k){if(x<0)putchar('-'),x=-x;x+=0.5*pow(10,-k);ull n=x;write(n);if(k>0){putchar('.');x-=n;For(i,1,k){x*=10;int c=(int)x;putchar(c+48);x-=c;}}}[[deprecated]]void write(float x){writef(x,6);} [[deprecated]]void write(long double x){writef(x,6);} [[deprecated]]void write(double x){writef(x,6);}template<size_t N>void write(std::bitset<N>b){write(b.to_string());}template<typename T,typename ...Tp>void write(T x,Tp ...y){write(x),write(y...);}template<typename T,typename ...Tp>void read(T &x,Tp &...y){read(x),read(y...);}struct FstIO{bool s=1;void flush(){fwrite(outBuffer,outPtr-outBuffer,1,stdout);outPtr=outBuffer;}~FstIO(){flush();}explicit operator bool()const{return s;}}io;template<typename T>FstIO&operator>>(FstIO&i,T&b){i.s=read(b);return i;}template<typename T>FstIO&operator<<(FstIO&i,T b){write(b);return i;}}using namespace fast_IO;void freopen(string name="test",int type=1,string aaa="",string bbb=""){if(type==1){freopen((name+".in").c_str(),"r",stdin),freopen((name+".out").c_str(),"w",stdout);}else if(type==2){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"w",stdout);}else if(type==3){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"wb",stdout);}else if(type==4){freopen((name+aaa).c_str(),"wb",stdout);}else{return;}}class FastRand{private:ull s[4];ull rotl(const ull x,int k){return(x<<k)|(x>>(64-k));}ull next(){const ull res=rotl(s[0]+s[3],23)+s[0];const ull t=s[1]<<17;s[2]^=s[0];s[3]^=s[1];s[1]^=s[2];s[0]^=s[3];s[2]^=t;s[3]=rotl(s[3],45);return res;}public:FastRand(){mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());For(i,0,3)s[i]=rng();}int randint(int l,int r){ull range=(ull)r-l+1,v;if(range==0)return next();ull mask=(1ULL<<(64-__builtin_clzll(range-1)))-1;while((v=(next()&mask))>=range);return v+l;}double frand(double l,double r){const union {ull i;double d;}u={.i=0x3FF0000000000000ULL|(next()>>12)};return (u.d-1.0)*(r-l)+l;}}Rand;```:::::::::::success[数据结构]:::info[文艺平衡树(1016B)]FHQ Treap。```cppstruct Node{int l,r,v,val,sz,rev;}t[N];int rt,cnt;void up(int id){t[id].sz=t[t[id].l].sz+t[t[id].r].sz+1;}void down(int id){if(t[id].rev){swap(t[id].l,t[id].r);if(t[id].l)t[t[id].l].rev^=1;if(t[id].r)t[t[id].r].rev^=1;t[id].rev=0;}}int newNode(int v){t[++cnt]={0,0,v,Rand.randint(1,1e9),1,0};return cnt;}void split(int id,int k,int &x,int &y){if(!id){x=y=0;return;}down(id);if(t[t[id].l].sz<k)x=id,split(t[id].r,k-t[t[id].l].sz-1,t[x].r,y);elsey=id,split(t[id].l,k,x,t[y].l);up(id);}int merge(int x,int y){if(!x||!y)return x|y;if(t[x].val>t[y].val){down(x);t[x].r=merge(t[x].r,y);up(x);return x;}else{down(y);t[y].l=merge(x,t[y].l);up(y);return y;}}void reverse(int l,int r){int x,y,z;split(rt,r,x,z);split(x,l-1,x,y);t[y].rev^=1;rt=merge(merge(x,y),z);}void out(int id){if(!id)return;down(id);out(t[id].l);cout<<t[id].v<<" ";out(t[id].r);}```::::::info[普通平衡树(76B)]```cpptree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update> st;```::::::info[Weight Balanced Leafy Tree]```cppconstexpr int N=5e5+5,MOD=998244353,alpha=29;struct Node{int ch[2],val,sz;}d[N];#define ls ch[0]#define rs ch[1]int root,tot;int newnode(int v){d[++tot].sz=1;d[tot].val=v;d[tot].ls=d[tot].rs=0;return tot;}bool ifleaf(int p){return !d[p].ls&&!d[p].rs;}void pushup(int p){if(ifleaf(p))return;d[p].sz=d[d[p].ls].sz+d[d[p].rs].sz;d[p].val=d[d[p].rs].val;}void pushdown(int p){}void delnode(int p){}void rotate(int p,int dir){swap(d[p].ls,d[p].rs);swap(d[d[p].ch[!dir]].ls,d[d[p].ch[!dir]].rs);swap(d[d[p].ch[!dir]].ch[!dir],d[p].ch[dir]);pushup(d[p].ls);pushup(d[p].rs);pushup(p);}void maintain(int p){if(ifleaf(p))return;int k=-1;if(d[d[p].ls].sz*100<d[p].sz*alpha)k=1;else if(d[d[p].rs].sz*100<d[p].sz*alpha)k=0;if(k==-1)return;if(d[d[d[p].ch[k]].ch[!k]].sz*(100-alpha)>=d[d[p].ch[k]].sz*(100-2*alpha))rotate(d[p].ch[k],!k);rotate(p,k);}void insert(int v,int p){if(!root){root=newnode(v);return;}if(ifleaf(p)){int s1=newnode(d[p].val),s2=newnode(v);if(d[p].val>v)swap(s1,s2);d[p].ls=s1;d[p].rs=s2;}else{if(d[d[p].ls].val>=v)insert(v,d[p].ls);else insert(v,d[p].rs);}pushup(p);maintain(p);}void del(int &p,int v){if(!p)return;if(ifleaf(p)){if(d[p].val==v)p=0;return;}if(d[d[p].ls].val>=v){if(ifleaf(d[p].ls)){if(d[d[p].ls].val==v)p=d[p].rs;}else{del(d[p].ls,v);pushup(p);maintain(p);}}else{if(ifleaf(d[p].rs)){if(d[d[p].rs].val==v)p=d[p].ls;}else{del(d[p].rs,v);pushup(p);maintain(p);}}}int queryrank(int v){if(!root)return 1;int p=root,ans=0;while(p){if(ifleaf(p))return d[p].val<v?ans+2:ans+1;if(d[d[p].ls].val>=v)p=d[p].ls;else{ans+=d[d[p].ls].sz;p=d[p].rs;}}return ans;}int queryval(int k){int p=root;while(p){if(ifleaf(p))return d[p].val;if(d[d[p].ls].sz>=k)p=d[p].ls;else{k-=d[d[p].ls].sz;p=d[p].rs;}}return -1;}int askpre(int v){return queryval(queryrank(v)-1);}int asknext(int v){return queryval(queryrank(v+1));}int merge(int x,int y){if(!x||!y)return x|y;int t=d[x].sz+d[y].sz;if(min(d[x].sz,d[y].sz)>=alpha*t){int p=newnode(0);d[p].ls=x;d[p].rs=y;pushup(p);return p;}if(d[x].sz>=d[y].sz){pushdown(x);if(d[d[x].ls].sz>=alpha*t){d[x].rs=merge(d[x].rs,y);pushup(x);return x;}pushdown(d[x].rs);d[x].ls=merge(d[x].ls,d[d[x].rs].ls);delnode(d[x].rs);d[x].rs=merge(d[d[x].rs].rs,y);pushup(x);return x;}pushdown(y);if(d[d[y].rs].sz>=alpha*t){d[y].ls=merge(x,d[y].ls);pushup(y);return y;}pushdown(d[y].ls);d[y].rs=merge(d[d[y].ls].rs,d[y].rs);delnode(d[y].ls);d[y].ls=merge(x,d[d[y].ls].ls);pushup(y);return y;}void splitval(int p,int k,int &x,int &y){if(!p){x=y=0;return;}if(ifleaf(p)){if(d[p].val<=k)x=p,y=0;else x=0,y=p;return;}pushdown(p);if(k>=d[d[p].ls].val){splitval(d[p].rs,k,x,y);delnode(p);x=merge(d[p].ls,x);}else{splitval(d[p].ls,k,x,y);delnode(p);y=merge(y,d[p].rs);}}void splitsz(int p,int k,int &x,int &y){if(!p){x=y=0;return;}if(k==0){x=0;y=p;return;}if(ifleaf(p)){if(k)x=p,y=0;else x=0,y=p;return;}pushdown(p);if(k>=d[d[p].ls].sz){splitsz(d[p].rs,k-d[d[p].ls].sz,x,y);delnode(p);x=merge(d[p].ls,x);}else{splitsz(d[p].ls,k,x,y);delnode(p);y=merge(y,d[p].rs);}}```::::::info[线段树]WIP::::::info[树链剖分(3182B)]```cppvector<int> g[N];int n,m,rint dep[N],fa[N],sz[N],ch[N],q[N],a[N],id[N],top[N];void dfs1(int u,int fat,int dp){sz[u]=1;dep[u]=dp;fa[u]=fat;for(auto v:g[u]){if(v==fat) continue;dfs1(v,u,dp+1);sz[u]+=sz[v];if(sz[v]>sz[ch[u]])ch[u]=v;}}void dfs2(int u,int tp){id[u]=++cnt;a[cnt]=q[u];top[u]=tp;if(ch[u]){dfs2(ch[u],tp);for(int v:g[u]){if(v==fa[u]||v==ch[u]) continue;dfs2(v,v);}}}#define dis(id) (tree[id].r-tree[id].l+1)#define ls (id<<1)#define rs (id<<1|1)#define tree treeovostruct Node{int l,r,sum,lz;}tree[N<<2];void pushDown(int id){int lz=tree[id].lz;if(lz){tree[ls].sum+=dis(ls)*lz,tree[rs].sum+=dis(rs)*lz;tree[ls].lz+=lz,tree[rs].lz+=lz;tree[id].lz=0;}}void pushUp(int id){tree[id].sum=tree[ls].sum+tree[rs].sum;}void build(int id,int l,int r){tree[id].l=l,tree[id].r=r;if(l==r)return tree[id].sum=a[l],void();int mid=l+r>>1;build(ls,l,mid);build(rs,mid+1,r);pushUp(id);}int query(int id,int l,int r){if(tree[id].l>=l&&r>=tree[id].r)return tree[id].sum;int mid=tree[id].l+tree[id].r>>1,ans=0;pushDown(id);if(l<=mid)ans+=query(ls,l,r);if(mid<r)ans+=query(rs,l,r);return ans%p;}void upd(int id,int l,int r,int k){if(tree[id].l>=l&&r>=tree[id].r){tree[id].sum+=dis(id)*k;tree[id].lz+=k;return;}int mid=tree[id].l+tree[id].r>>1;pushDown(id);if(l<=mid)upd(ls,l,r,k);if(mid<r)upd(rs,l,r,k);pushUp(id);}#undef ls#undef rs#undef tree#undef disvoid debugfs(int u,int fat){cout<<"Point "<<u<<" statistics: ";cout<<"Father = "<<fa[u]<<" Depth = "<<dep[u]<<" Size = "<<sz[u]<<" Big Son = "<<ch[u]<<" Top of chain = "<<top[u]<<" dfs Order = "<<id[u]<<'\n';for(int i:g[u]){if(i==fat) continue;debugfs(i,u);}}int chainQ(int u,int v){int ans=0;while(top[u]!=top[v]){if(dep[top[u]]<dep[top[v]]) swap(u,v);ans+=query(1,id[top[u]],id[u]);ans%=p;u=fa[top[u]];}if(dep[u]>dep[u]) swap(u,v);ans+=query(1,id[u],id[v]);return ans%p;}void chainUpd(int u,int v,int k){k%=p;while(top[u]!=top[v]){if(dep[top[u]]<dep[top[v]]) swap(u,v);upd(1,id[top[u]],id[u],k);u=fa[top[u]];}if(dep[u]>dep[v]) swap(u,v);upd(1,id[u],id[v],k);}int treeQ(int u){return query(1,id[u],id[u]+sz[u]-1);}void treeUpd(int u,int k){k%=p;upd(1,id[u],id[u]+sz[u]-1,k);}Int main(){timer.restart();cin>>n>>m>>r>>p;For(i,1,n)cin>>q[i];For(i,2,n){int x,y;cin>>x>>y;g[x].pb(y);g[y].pb(x);}dfs1(r,0,1);dfs2(r,r);build(1,1,n);For(i,1,m){int op;cin>>op;if(op==1){int u,v,w;cin>>u>>v>>w;chainUpd(u,v,w);}if(op==2){int u,v;cin>>u>>v;cout<<chainQ(u,v)<<'\n';}if(op==3){int x,k;cin>>x>>k;treeUpd(x,k);}if(op==4){int x;cin>>x;cout<<treeQ(x)<<'\n';}}Happy Ending;}```:::::::::::success[插件]:::info[background]```js// ==UserScript==// @name 洛谷 / GOJ - 自定义背景// @namespace https://www.luogu.com.cn/// @version 1.03.7// @description 为洛谷和 GOJ 自定义图片、视频背景与区域透明度。// @author ?// @license MIT// @match https://www.luogu.com.cn/*// @match https://www.luogu.com/*// @match *://www.goj.wiki/*// @match *://goj.wiki/*// @grant GM_addStyle// @grant GM_getValue// @grant GM_setValue// @require https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js// @run-at document-idle// ==/UserScript==(function () {'use strict';const IS_GOJ = /^(www\.)?goj\.wiki$/.test(location.hostname);const SETTING_PREFIX = IS_GOJ ? `goj:${location.origin}:` : '';const DB_NAME = 'LuoguBgDB' , STORE_NAME = 'media';function openDB() {return new Promise((resolve , reject) => {const r = indexedDB.open(DB_NAME , 1);r.onupgradeneeded = e => {const db = e.target.result;if(!db.objectStoreNames.contains(STORE_NAME)){db.createObjectStore(STORE_NAME , { keyPath: 'id' , autoIncrement: true });}};r.onsuccess = e => resolve(e.target.result);r.onerror = e => reject(e.target.error);});}async function dbAdd(media){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readwrite') , store = tx.objectStore(STORE_NAME) , req = store.add(media);return new Promise((res , rej) => {tx.oncomplete = () => res(req.result);tx.onerror = rej;req.onerror = rej;});}async function dbGet(id){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readonly') , store = tx.objectStore(STORE_NAME) , req = store.get(Number(id));return new Promise((res , rej) => {req.onsuccess = () => res(req.result);req.onerror = rej;});}async function dbDelete(id){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readwrite') , store = tx.objectStore(STORE_NAME);store.delete(Number(id));return new Promise((res , rej) => {tx.oncomplete = res;tx.onerror = rej;});}async function dbClear(){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readwrite') , store = tx.objectStore(STORE_NAME);store.clear();return new Promise((res , rej) => {tx.oncomplete = res;tx.onerror = rej;});}async function dbUpdate(id , updates){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readwrite') , store = tx.objectStore(STORE_NAME);const getReq = store.get(Number(id));getReq.onsuccess = () => {const m = getReq.result;if(m)Object.assign(m , updates);store.put(m);};return new Promise((res , rej) => {tx.oncomplete = res;tx.onerror = rej;});}async function dbAllMedia(){const db = await openDB() , tx = db.transaction(STORE_NAME , 'readonly') , store = tx.objectStore(STORE_NAME) , req = store.getAll();return new Promise((res , rej) => {req.onsuccess = () => res(req.result);req.onerror = rej;});}function blob2buf(blob){return new Promise((res , rej) => {const r = new FileReader();r.onload = () => res(r.result);r.onerror = rej;r.readAsArrayBuffer(blob);});}// 根据存储的数据生成 URL。图片存储 Data URL 字符串,视频存储 ArrayBufferfunction media2url(media) {if (media.type === 'image' && typeof media.data === 'string') {return media.data; // Data URL}// 视频或旧版 ArrayBuffer 图片return URL.createObjectURL(new Blob([media.data] , { type: media.mime }));}const DEFAULTS = {blur: 0 , navOpacity: 0.82 , cardOpacity: 0.88 , footerOpacity: 0.70 ,bgBrightness: 1.0 , bgSaturation: 1.0 ,articleTransparent: true , globalGlass: false ,randomBg: true , currentBgId: null ,enableBgLayer: true , panelCollapsed: false};const MAX = 30;let currentSettings;function loadSettings(){if(currentSettings)return currentSettings;const s = {};for(const [k , d] of Object.entries(DEFAULTS)){const v = GM_getValue(SETTING_PREFIX + k , undefined);s[k] = (v !== undefined && v !== null) ? v : d;}return currentSettings = s;}function saveSettings(s){Object.entries(s).forEach(([k , v]) => GM_setValue(SETTING_PREFIX + k , v));}const clamp = (v , min , max) => Math.max(min , Math.min(max , v));let saving = false;function toast(status){let el = document.getElementById('luogu-upload-toast');if(!el){el = document.createElement('div');el.id = 'luogu-upload-toast';el.style.cssText = 'position:fixed;bottom:30px;right:30px;z-index:999999;padding:12px 20px;border-radius:8px;color:#fff;font-size:14px;box-shadow:0 4px 12px rgba(0,0,0,0.2);transition:opacity 0.3s;opacity:0;pointer-events:none;';document.body.appendChild(el);}if(status === 'start'){saving = true;el.textContent = '⏳ 保存中… 请勿离开';el.style.background = '#e67e22';el.style.opacity = '1';}else if (status === 'done'){saving = false;el.textContent = '✅ 已保存';el.style.background = '#2ecc71';el.style.opacity = '1';setTimeout(() => {if (el.textContent === '✅ 已保存') {el.style.opacity = '0';}} , 2000);}}addEventListener('beforeunload' , e => {if (saving) {e.preventDefault();e.returnValue = '保存中背景图,离开将丢失背景';}});function injectStyles() {GM_addStyle(`.cropper-container{direction:ltr;font-size:0;line-height:0;position:relative;touch-action:none;user-select:none}.cropper-container img{display:block;height:100%;image-orientation:0deg;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}.cropper-wrap-box,.cropper-canvas,.cropper-drag-box,.cropper-crop-box,.cropper-modal{bottom:0;left:0;position:absolute;right:0;top:0}.cropper-wrap-box,.cropper-canvas{overflow:hidden}.cropper-drag-box{background-color:#fff;opacity:0}.cropper-modal{background-color:#000;opacity:.5}.cropper-view-box{display:block;height:100%;outline:1px solid #39f;outline-color:rgba(51,153,255,.75);overflow:hidden;width:100%}.cropper-dashed{border:0 dashed #eee;display:block;opacity:.5;position:absolute}.cropper-dashed.dashed-h{border-bottom-width:1px;border-top-width:1px;height:33.33%;left:0;top:33.33%;width:100%}.cropper-dashed.dashed-v{border-left-width:1px;border-right-width:1px;height:100%;left:33.33%;top:0;width:33.33%}.cropper-center{display:block;height:0;left:50%;opacity:.75;position:absolute;top:50%;width:0}.cropper-center:before,.cropper-center:after{background-color:#eee;content:' ';display:block;position:absolute}.cropper-center:before{height:1px;left:-3px;top:0;width:7px}.cropper-center:after{height:7px;left:0;top:-3px;width:1px}.cropper-face,.cropper-line,.cropper-point{display:block;height:100%;opacity:.1;position:absolute;width:100%}.cropper-face{background-color:#fff;left:0;top:0}.cropper-line{background-color:#39f}.cropper-line.line-e{cursor:ew-resize;right:-3px;top:0;width:5px}.cropper-line.line-n{cursor:ns-resize;height:5px;left:0;top:-3px}.cropper-line.line-w{cursor:ew-resize;left:-3px;top:0;width:5px}.cropper-line.line-s{bottom:-3px;cursor:ns-resize;height:5px;left:0}.cropper-point{background-color:#39f;height:5px;opacity:.75;width:5px}.cropper-point.point-e{cursor:ew-resize;margin-top:-3px;right:-3px;top:50%}.cropper-point.point-n{cursor:ns-resize;left:50%;margin-left:-3px;top:-3px}.cropper-point.point-w{cursor:ew-resize;left:-3px;margin-top:-3px;top:50%}.cropper-point.point-s{bottom:-3px;cursor:s-resize;left:50%;margin-left:-3px}.cropper-point.point-ne{cursor:nesw-resize;right:-3px;top:-3px}.cropper-point.point-nw{cursor:nwse-resize;left:-3px;top:-3px}.cropper-point.point-sw{bottom:-3px;cursor:nesw-resize;left:-3px}.cropper-point.point-se{bottom:-3px;cursor:nwse-resize;height:20px;opacity:1;right:-3px;width:20px}@media(min-width:768px){.cropper-point.point-se{height:15px;width:15px}}@media(min-width:992px){.cropper-point.point-se{height:10px;width:10px}}@media(min-width:1200px){.cropper-point.point-se{height:5px;opacity:.75;width:5px}}.cropper-point.point-se:before{background-color:#39f;bottom:-50%;content:' ';display:block;height:200%;opacity:0;position:absolute;right:-50%;width:200%}.cropper-invisible{opacity:0}.cropper-bg{background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEUAAAD///+l2Z/dAAAAMUlEQVQI12P4//8/Aw3zf7CoWcPAf+BABsz3zw0M/B8YmB8+MDD/f2B4P2FQ/GBQAAAkNxI0kX/LBgAAAABJRU5ErkJggg==')}.cropper-hide{display:block;height:0;position:absolute;width:0}.cropper-hidden{display:none!important}.cropper-move{cursor:move}.cropper-crop{cursor:crosshair}.cropper-disabled .cropper-drag-box,.cropper-disabled .cropper-face,.cropper-disabled .cropper-line,.cropper-disabled .cropper-point{cursor:not-allowed}/* Keep background layers behind content without changing layout positioning. */html, body { background: transparent !important; }body { isolation: isolate; }#app, .lfe-body { background: transparent !important; }/* Clear outer layout backgrounds while preserving card opacity settings. */main, .main-container, .lside-nav, .main-container.lside-nav,.theme-page, .theme-page.no-header, #app-old {background-color: transparent !important;background-image: none !important;}.theme-page::before, .theme-page::after,.theme-page.no-header::before, .theme-page.no-header::after,body::before, body::after { background: none !important; }#luogu-bg-layer{position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:-2;pointer-events:none;overflow:hidden;background:#1a1a2e!important;opacity:1!important}#luogu-bg-layer .bg-inner{position:absolute;top:-30px;left:-30px;width:calc(100% + 60px);height:calc(100% + 60px);background-size:cover;background-position:center;background-repeat:no-repeat;transition:filter 0.4s ease}#luogu-bg-layer video{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover}#luogu-glass-overlay{position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:-1;background:transparent;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);display:none}:root{--lgb-nav-opacity:0.82;--lgb-card-opacity:0.88;--lgb-footer-opacity:0.70}.top-bar{background-color:rgba(255,255,255,var(--lgb-nav-opacity))!important;backdrop-filter:blur(calc((1 - var(--lgb-nav-opacity)) * 8px));-webkit-backdrop-filter:blur(calc((1 - var(--lgb-nav-opacity)) * 8px))}.sidebar.lside,.rside{background-color:rgba(255,255,255,var(--lgb-nav-opacity))!important;backdrop-filter:blur(calc((1 - var(--lgb-nav-opacity)) * 8px));-webkit-backdrop-filter:blur(calc((1 - var(--lgb-nav-opacity)) * 8px))}.wrapper.header-layout .background{opacity:var(--lgb-nav-opacity)!important}footer{background-color:rgba(255,255,255,var(--lgb-footer-opacity))!important;backdrop-filter:blur(calc((1 - var(--lgb-footer-opacity)) * 8px));-webkit-backdrop-filter:blur(calc((1 - var(--lgb-footer-opacity)) * 8px))}.wrapper.wrapped.lfe-body:not(.header-layout) .background{opacity:var(--lgb-footer-opacity)!important}.theme-page{--theme-body-image:none!important;--theme-body-back:transparent!important;background:transparent!important}main.lfe-body.mobile-body,main.lcolor-bg-background{background-color:transparent!important}.l-card,.lg-article,.am-panel,.lg-index-stat,.lg-index-contest,section.am-panel{background-color:rgba(255,255,255,var(--lgb-card-opacity))!important}.lg-index-contest .am-panel-bd{background-color:transparent!important}.user-header-top{background-color:unset!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}div[style*="background-color: rgb(255, 255, 255)"]{background-color:transparent!important}.l-card.type-burger,.l-card.type-burger{background-color:#fff!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}.article-banner{background-color:transparent!important}.top-progress{display:none!important}.am-modal-dialog,.dropdown,.am-dropdown-content,.am-selected-content,[class*="dropdown"],.user-nav .dropdown{background-color:rgba(255,255,255,0.98)!important;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}.search-wrap input{background-color:rgba(255,255,255,0.95)!important}.reply-item,.comment-item,.l-card.reply-item{background-color:rgba(255,255,255,0.65)!important}#luogu-cropper-modal{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:1000000}#luogu-cropper-modal .crop-container{background:#fff;border-radius:12px;padding:20px;max-width:95vw;max-height:90vh}#luogu-cropper-modal .crop-header{font-size:16px;font-weight:600;margin-bottom:12px;text-align:center}#luogu-cropper-modal .crop-body{max-width:80vw;max-height:60vh;overflow:hidden}#luogu-cropper-modal .crop-body img{max-width:100%;display:block}#luogu-cropper-modal .crop-footer{margin-top:12px;display:flex;justify-content:flex-end;gap:8px}#luogu-cropper-modal button{padding:8px 16px;border:none;border-radius:6px;cursor:pointer;font-size:13px}#luogu-cropper-modal .btn-cancel{background:#f0f0f0;color:#333}#luogu-cropper-modal .btn-confirm{background:#3498db;color:#fff}.bg-upload-btn{display:inline-block;padding:6px 12px;background:#f0f0f0;border:1px solid #ddd;border-radius:6px;cursor:pointer;font-size:12px}.bg-upload-btn:hover{background:#e0e0e0}.bg-image-list{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}.bg-image-item{position:relative;width:50px;height:50px;border-radius:6px;overflow:hidden;border:1px solid #ddd;cursor:pointer}.bg-image-item img{width:100%;height:100%;object-fit:cover}.bg-image-item .video-icon{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:24px;background:#f0f0f0}.bg-image-item .delete-btn{position:absolute;top:0;right:0;background:rgba(231,76,60,0.8);color:#fff;border:none;width:18px;height:18px;font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:0 6px 0 6px;z-index:1}.bg-image-item .loop-toggle{position:absolute;bottom:0;left:0;background:rgba(0,0,0,0.5);color:#fff;border:none;width:18px;height:18px;font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:0 0 6px 0;z-index:1}#luogu-bg-panel{position:fixed;top:50%;right:24px;z-index:99998;transform:translateY(-50%);width:320px;max-width:calc(100vw - 48px);max-height:80vh;overflow-y:auto;background:rgba(255,255,255,0.97);border-radius:16px;box-shadow:0 8px 40px rgba(0,0,0,0.2);padding:20px 18px 16px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;font-size:13px;color:#333;transition:all 0.35s cubic-bezier(0.4,0,0.2,1);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);scrollbar-width:thin;scrollbar-color:#ccc transparent}#luogu-bg-panel.collapsed{opacity:0;pointer-events:none;transform:translateY(-50%) translateX(120%)}#luogu-bg-panel h3{margin:0 0 14px;font-size:16px;font-weight:700;color:#2c3e50;text-align:center}#luogu-bg-panel .section-title{font-size:12px;font-weight:600;color:#7f8c8d;margin:14px 0 8px;padding-top:10px;border-top:1px solid #eee;cursor:pointer;display:flex;align-items:center;justify-content:space-between}#luogu-bg-panel .section-title:first-of-type{border-top:none;margin-top:4px;padding-top:0}#luogu-bg-panel .section-title .arrow{transition:transform 0.3s;font-size:14px}#luogu-bg-panel .section-title.collapsed .arrow{transform:rotate(-90deg)}#luogu-bg-panel .settings-block{overflow:hidden;transition:max-height 0.4s ease}#luogu-bg-panel .settings-block.collapsed{max-height:0!important}#luogu-bg-panel input[type="url"],#luogu-bg-panel input[type="text"]{width:100%;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-size:12px;background:#fdfdfd}#luogu-bg-panel input:focus{outline:none;border-color:#3498db}#luogu-bg-panel .slider-group{display:flex;align-items:center;gap:10px;margin:6px 0}#luogu-bg-panel .slider-group label{min-width:60px;font-size:12px;color:#555;text-align:right}#luogu-bg-panel .slider-group input[type="range"]{flex:1;-webkit-appearance:none;height:6px;border-radius:3px;background:#e0e0e0}#luogu-bg-panel .slider-group input[type="range"]::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border-radius:50%;background:#3498db;border:2px solid #fff}#luogu-bg-panel .slider-group .val-display{min-width:40px;text-align:center;font-size:11px;font-weight:600;color:#2980b9;background:#eaf4fb;padding:3px 6px;border-radius:6px}#luogu-bg-panel .btn-row{display:flex;gap:8px;margin-top:14px}#luogu-bg-panel .btn-row button{flex:1;padding:9px 0;border-radius:8px;border:none;font-weight:600;cursor:pointer}#luogu-bg-panel .btn-reset{background:#f5f5f5;color:#666;border:1px solid #ddd}#luogu-bg-panel .btn-reset:hover{background:#e8e8e8}#luogu-bg-panel .btn-clearall{background:#e74c3c;color:#fff}#luogu-bg-panel .btn-clearall:hover{background:#c0392b}#luogu-bg-panel .btn-close{width:100%;margin-top:4px;padding:8px;background:#f5f5f5;color:#888;border:1px solid #ddd;border-radius:8px;cursor:pointer}#luogu-bg-panel .btn-close:hover{background:#e0e0e0}`);}function injectGojStyles() {GM_addStyle(`html.lgb-goj{--lgb-surface:255,255,255;--lgb-nav-surface:255,255,255;--lgb-nav-text:85,85,85}html.lgb-goj.theme--dark{--lgb-surface:50,51,52;--lgb-nav-surface:50,51,52;--lgb-nav-text:238,238,238}html.lgb-goj #panel,html.lgb-goj #panel>.main{background:transparent!important}html.lgb-goj .section:not(.section--contest),html.lgb-goj .section__table-header{background-color:rgba(var(--lgb-surface),var(--lgb-card-opacity))!important}html.lgb-goj .nav{background-color:rgba(var(--lgb-nav-surface),var(--lgb-nav-opacity))!important;color:rgb(var(--lgb-nav-text))}html.lgb-goj .header--mobile,html.lgb-goj .location{background-color:rgba(86,117,143,var(--lgb-nav-opacity))!important}html.lgb-goj .footer{background-color:rgba(var(--lgb-surface),var(--lgb-footer-opacity))!important;color:rgb(var(--lgb-nav-text))!important}html.lgb-goj .dialog__content,html.lgb-goj .dropdown,html.lgb-goj .dropdown-target,html.lgb-goj .drop-element .menu{background-color:rgba(var(--lgb-surface),0.98)!important}html.lgb-goj.layout--immersive .footer{background-color:rgba(30,40,55,var(--lgb-footer-opacity))!important;color:#fff!important}html.lgb-goj #luogu-bg-panel,html.lgb-goj #luogu-bg-panel *{box-sizing:border-box}html.lgb-goj #luogu-bg-panel input{color:#333}#luogu-bg-toggle{position:fixed;right:20px;bottom:20px;z-index:99997;padding:10px 16px;border:1px solid #ddd;border-radius:20px;background:rgba(255,255,255,0.95);color:#333;box-shadow:0 2px 12px rgba(0,0,0,0.15);font:14px sans-serif;cursor:pointer}@media(max-width:600px){html.lgb-goj .nav{--lgb-nav-surface:86,117,143;--lgb-nav-text:255,255,255}html.lgb-goj .nav .dropdown-target.menu{background:transparent!important}}`);}function injectArticleStyles() {GM_addStyle(`html.lgb-columba #app .theme-page{--theme-body-back:transparent!important;--theme-body-image:none!important;--theme-card-background:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-card-opacity))!important;--theme-card-backdrop-filter:none!important}html.lgb-columba #app :is(.main-container,.theme-page,.main-content,.sidebar-container,.columba-content-wrap:not(.l-card):not(.article-content)){background:transparent!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html.lgb-columba #app .theme-page::before,html.lgb-columba #app .theme-page::after{background:none!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html.lgb-columba #app .l-card{background-color:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-card-opacity))!important}html.lgb-columba #app .theme-frosted .l-card::before{background:transparent!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html.lgb-columba #app .top-bar,html.lgb-columba #app .sidebar.lside,html.lgb-columba #app .rside,html.lgb-columba #app .user-nav{background:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-nav-opacity))!important}html.lgb-columba #app footer{background:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-footer-opacity))!important}html.lgb-columba #app .inner-card,html.lgb-columba #app .reply-item,html.lgb-columba #app .comment-item,html.lgb-columba #app .article-content .actions.left-mode,html.lgb-columba #app .bottom-wrap.float{background:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-card-opacity))!important}html.lgb-columba #app .reply-item>.meta,html.lgb-columba #app .reply-item .main>.meta{background:transparent!important}html.lgb-columba #app input:not([type=range]):not([type=checkbox]):not([type=radio]),html.lgb-columba #app textarea,html.lgb-columba #app .refined-input,html.lgb-columba #app .combo-wrapper>.text{background:rgba(var(--lcolor--bg-container,255,255,255),var(--lgb-card-opacity))!important}html.lgb-columba #app pre[class*="language-"],html.lgb-columba #app .lfe-code{background:rgba(var(--lcolor--fill-4,250,250,250),var(--lgb-card-opacity))!important}html.lgb-columba #app pre[class*="language-"]>code{background:transparent!important}html.lgb-columba #app .dropdown,html.lgb-columba #app .dropdown-operations,html.lgb-columba #app .setting-dropdown,html.lgb-columba #app .section-list-container{background:rgba(var(--lcolor--bg-elevated,255,255,255),0.98)!important}html.lgb-columba[data-lgb-article-page] #app div:has(>.article-content){background:transparent!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html.lgb-columba[data-lgb-article-page] #app .article-content{background:transparent!important}#luogu-bg-toggle{position:fixed;right:20px;bottom:20px;z-index:99997;padding:10px 16px;border:1px solid #ddd;border-radius:20px;background:rgba(255,255,255,0.95);color:#333;box-shadow:0 2px 12px rgba(0,0,0,0.15);font:14px sans-serif;cursor:pointer}`);}function createLayer() {let el = document.getElementById('luogu-bg-layer');if (el) {el.remove();}el = document.createElement('div');el.id = 'luogu-bg-layer';el.innerHTML = '<div class="bg-inner"></div>';document.body.insertBefore(el , document.body.firstChild);}function updateGlassOverlay(s) {let overlay = document.getElementById('luogu-glass-overlay');const isArticle = /^\/article\/[a-z0-9]{8}\/?$/i.test(location.pathname);const shouldShow = s.globalGlass || (!IS_GOJ && isArticle && !s.articleTransparent);if(shouldShow){if(!overlay){overlay = document.createElement('div');overlay.id = 'luogu-glass-overlay';document.body.insertBefore(overlay , document.body.firstChild);}overlay.style.display = 'block';}else if(overlay){overlay.style.display = 'none';}}const articleStyles = new Map();function clearArticleBackground(){if(IS_GOJ)return;const app = document.getElementById('app');const active = /^\/article\/[a-z0-9]{8}\/?$/i.test(location.pathname);document.documentElement.toggleAttribute('data-lgb-article-page' , active);const nodes = new Set();if(active && app)app.querySelectorAll('.article-content,.solution-article,.article-banner').forEach(el => {for(; el && app.contains(el); el = el.parentElement){nodes.add(el);if(el === app)break;}});for(const [el , props] of articleStyles){if(nodes.has(el))continue;for(const [key , val , priority] of props){const own = key === 'background' ? 'transparent' : 'none';if(el.style.getPropertyValue(key) === own && el.style.getPropertyPriority(key) === 'important'){if(val)el.style.setProperty(key , val , priority);elseel.style.removeProperty(key);}}el.removeAttribute('data-lgb-article-layout');articleStyles.delete(el);}for(const el of nodes){const props = [['background' , 'transparent'], ['backdrop-filter' , 'none'], ['-webkit-backdrop-filter' , 'none'], ['box-shadow' , 'none']];if(!articleStyles.has(el))articleStyles.set(el , props.map(([key]) => [key , el.style.getPropertyValue(key) , el.style.getPropertyPriority(key)]));el.setAttribute('data-lgb-article-layout' , '');for(const [key , val] of props){if(el.style.getPropertyValue(key) !== val || el.style.getPropertyPriority(key) !== 'important')el.style.setProperty(key , val , 'important');}}}async function setBackgroundById(id , s){const media = await dbGet(id);if(!media)return;const layer = document.getElementById('luogu-bg-layer');if(!layer)return;const inner = layer.querySelector('.bg-inner');if(!inner)return;if(!s.enableBgLayer){layer.style.display = 'none';return;}layer.style.display = '';inner.innerHTML = '';inner.style.backgroundImage = '';const oldVid = layer.querySelector('video');if(oldVid)oldVid.remove();try{const url = media2url(media);if(media.type === 'image'){inner.style.backgroundImage = `url(${url})`;}else if(media.type === 'video'){const v = document.createElement('video');v.src = url;v.autoplay = true;v.muted = true;v.playsInline = true;v.loop = media.loop !== false;v.style.pointerEvents = 'none';layer.appendChild(v);}}catch (e){console.error(e);}applyFilters(inner , s);s.currentBgId = id;saveSettings(s);}async function updateBg(s){const layer = document.getElementById('luogu-bg-layer');if(!layer)return;const inner = layer.querySelector('.bg-inner');if(!inner)return;if(!s.enableBgLayer){layer.style.display = 'none';return;}layer.style.display = '';inner.innerHTML = '';inner.style.backgroundImage = '';const oldVid = layer.querySelector('video');if(oldVid){oldVid.remove();}const allMedia = await dbAllMedia();if(!allMedia.length){inner.style.backgroundImage = 'linear-gradient(135deg, #1a1a2e 0%, #16213e 30%, #0f3460 60%, #1a1a2e 100%)';applyFilters(inner , s);return;}const now = Date.now();let selectedId = s.currentBgId;if(s.randomBg || !selectedId || !allMedia.some(m => m.id == selectedId)){const weights = allMedia.map(m => Math.max(1 , now - (m.lastUsed || 0)));const total = weights.reduce((a , b) => a + b , 0);let rand = Math.random() * total , idx = 0;for(let i = 0 ; i < weights.length ; i++){rand -= weights[i];if(rand <= 0){idx = i;break;}}selectedId = allMedia[idx].id;s.currentBgId = selectedId;saveSettings(s);}const media = allMedia.find(m => m.id == selectedId);if(!media)return;await dbUpdate(selectedId , { lastUsed: now });try{const url = media2url(media);if(media.type === 'image'){inner.style.backgroundImage = `url(${url})`;}else if(media.type === 'video'){const v = document.createElement('video');v.src = url;v.autoplay = true;v.muted = true;v.playsInline = true;v.loop = media.loop !== false;v.style.pointerEvents = 'none';layer.appendChild(v);}}catch (e){console.error(e);}applyFilters(inner , s);}function applyFilters(inner , s){const f = [];if(s.blur > 0)f.push(`blur(${s.blur}px)`);if(s.bgBrightness !== 1.0)f.push(`brightness(${s.bgBrightness})`);if(s.bgSaturation !== 1.0)f.push(`saturate(${s.bgSaturation})`);inner.style.filter = f.join(' ') || 'none';const video = inner.parentElement.querySelector('video');if(video)video.style.filter = inner.style.filter;}// 核心修改逻辑:使用高优先级全局 Style 强力覆盖组件function updateSurfaces(s){if(IS_GOJ)return;const rgb = 'var(--lcolor--bg-container,255,255,255)';const groups = [['#app .l-card,#app .card,#app .inner-card,#app .lg-article,#app .am-panel,#app .reply-item,#app .comment-item,#app .article-content .actions.left-mode,#app .bottom-wrap.float,.lg-article,.am-panel,.lg-index-stat,.lg-index-contest' , s.cardOpacity],['#app .top-bar,#app .sidebar.lside,#app .rside,#app .user-nav' , s.navOpacity],['#app footer,body>footer' , s.footerOpacity]];for(const [query , opacity] of groups){document.querySelectorAll(query).forEach(el => {if(el.hasAttribute('data-lgb-article-layout'))return;const value = `rgba(${rgb},${opacity})`;if(el.style.getPropertyValue('background') !== value || el.style.getPropertyPriority('background') !== 'important')el.style.setProperty('background' , value , 'important');});}}function updateVars(s){const r = document.documentElement.style;r.setProperty('--lgb-nav-opacity' , s.navOpacity , 'important');r.setProperty('--lgb-card-opacity' , s.cardOpacity , 'important');r.setProperty('--lgb-footer-opacity' , s.footerOpacity , 'important');updateSurfaces(s);if(IS_GOJ)return;let style = document.getElementById('luogu-dynamic-theme-style');if (!style) {style = document.createElement('style');style.id = 'luogu-dynamic-theme-style';document.head.appendChild(style);}const css = `body #app div.theme-page.theme-frosted,.am-modal-dialog, .dropdown, .am-dropdown-content, .am-selected-content, [class*="dropdown"], .user-nav .dropdown {backdrop-filter: blur(0px) !important;}div.theme-page.theme-frosted {--theme-card-background: rgba(255, 255, 255, 0) !important;--theme-card-backdrop-filter: blur(1px) !important;}body #app input[data-v-62a70fee],body #app textarea[data-v-62a70fee],body #app .refined-input[data-v-62a70fee],body #app .solution-article .operations.float[data-v-1ab4f7de] {background: rgba(255, 255, 255, ${s.cardOpacity}) !important;}body #app .message-block > .message[data-v-5c0627c6],body #app .lfe-code {background-color: rgba(250, 250, 250, ${s.cardOpacity}) !important;}body pre[class*="language-"] {background: rgba(255, 255, 255, ${s.cardOpacity}) !important;}body .am-form input[type=number],body .am-form input[type=search],body .am-form input[type=text],body .am-form input[type=password],body .am-form input[type=datetime],body .am-form input[type=datetime-local],body .am-form input[type=date],body .am-form input[type=month],body .am-form input[type=time],body .am-form input[type=week],body .am-form input[type=email],body .am-form input[type=url],body .am-form input[type=tel],body .am-form input[type=color],body .am-form select,body .am-form textarea,body .bottom-wrap.float[data-v-2628cb00],body .marked[data-v-e5ad98f0] pre,body .am-form-field {background-color: rgba(255, 255, 255, ${s.cardOpacity}) !important;}body .marked[data-v-e5ad98f0] code,body .user-header-bottom[data-v-3c374c4c],body .comment .author[data-v-6526f140],body .article-content .actions.left-mode[data-v-0928b76c],.reply-item>.meta[data-v-634012de],body code[class*="language-"],body .log .author[data-v-696c242f],body #app input[data-v-62a70fee], body #app textarea[data-v-62a70fee], body #app .refined-input[data-v-62a70fee], body #app .solution-article .operations.float[data-v-1ab4f7de],body .combo-wrapper>.text[data-v-dbc33c63],body #app .comment .author[data-v-2323fc26]{background: rgba(255, 255, 255, 0) !important;}body .card[data-v-f9624136],body .am-modal-dialog,body .dropdown,body .am-dropdown-content,body .am-selected-content,body [class*="dropdown"],body .user-nav .dropdown {background-color: rgba(255, 255, 255, ${s.cardOpacity}) !important;}html:root body #app :is(.l-card,.card,.inner-card,.lg-article,.am-panel,.reply-item,.comment-item),html:root body #app .article-content .actions.left-mode,html:root body #app .bottom-wrap.float {background: rgba(var(--lcolor--bg-container,255,255,255), ${s.cardOpacity}) !important;}html:root body #app .theme-page.theme-frosted .l-card::before {background: transparent !important;backdrop-filter: none !important;-webkit-backdrop-filter: none !important;}html:root body #app :is(.top-bar,.sidebar.lside,.rside,.user-nav) {background: rgba(var(--lcolor--bg-container,255,255,255), ${s.navOpacity}) !important;}html:root body #app footer {background: rgba(var(--lcolor--bg-container,255,255,255), ${s.footerOpacity}) !important;}html:root[data-lgb-article-page] body #app .article-content,html:root[data-lgb-article-page] body #app div:has(>.article-content) {background: transparent !important;}html:root body #app[data-lgb-article-layout],html:root body #app [data-lgb-article-layout],html:root body #app [data-lgb-article-layout]::before,html:root body #app [data-lgb-article-layout]::after {background: transparent !important;backdrop-filter: none !important;-webkit-backdrop-filter: none !important;box-shadow: none !important;}`;if(style.textContent !== css)style.textContent = css;}async function apply(s , reload = true){clearArticleBackground();updateVars(s);updateGlassOverlay(s);if(reload){await updateBg(s);}else{const inner = document.querySelector('#luogu-bg-layer .bg-inner');if(inner)applyFilters(inner , s);}}function openFile(){const inp = document.createElement('input');inp.type = 'file';inp.accept = 'image/*,video/mp4';inp.addEventListener('change' , async e => {const f = e.target.files[0];if(!f)return;toast('start');try{if(f.type.startsWith('video/')){const buf = await blob2buf(f);const count = (await dbAllMedia()).length;if(count >= MAX){alert(`最多只能添加 ${MAX} 个媒体`);toast('done');return;}await dbAdd({ type: 'video' , mime: f.type , data: buf , loop: true , lastUsed: 0 });const s = loadSettings();await apply(s);refreshPanel();toast('done');}else{const reader = new FileReader();reader.onload = ev => startCropper(ev.target.result);reader.readAsDataURL(f);}}catch (er){console.error(er);toast('done');}});inp.click();}function startCropper(src){const modal = document.createElement('div');modal.id = 'luogu-cropper-modal';modal.innerHTML = `<div class="crop-container"><div class="crop-header"> 裁剪背景图片</div><div class="crop-body"><img id="luogu-crop-image"></div><div class="crop-footer"><button class="btn-cancel">取消</button><button class="btn-confirm">确认裁剪</button></div></div>`;document.body.appendChild(modal);const img = document.getElementById('luogu-crop-image');img.crossOrigin = 'anonymous';img.src = src;img.onload = () => {const aspect = innerWidth / innerHeight;const cropper = new Cropper(img , { aspectRatio: aspect , viewMode: 1 , dragMode: 'move' , autoCropArea: 0.8 , cropBoxMovable: true , cropBoxResizable: true , background: false });const close = () => {cropper.destroy();modal.remove();};modal.querySelector('.btn-cancel').addEventListener('click' , close);modal.addEventListener('click' , ev => {if(ev.target === modal)close();});modal.querySelector('.btn-confirm').addEventListener('click' , async () => {toast('start');try{const count = (await dbAllMedia()).length;if(count >= MAX){alert(`最多只能添加 ${MAX} 个媒体`);toast('done');close();return;}const maxW = Math.min(2560 , innerWidth * 2) , maxH = Math.round(maxW / aspect);const canvas = cropper.getCroppedCanvas({ maxWidth: maxW , maxHeight: maxH , fillColor: '#fff' , imageSmoothingQuality: 'high' });const dataUrl = canvas.toDataURL('image/jpeg' , 0.85);await dbAdd({ type: 'image' , data: dataUrl , lastUsed: 0 });const s = loadSettings();await apply(s);refreshPanel();}catch (er){console.error(er);}toast('done');close();});};img.onerror = () => {alert('图片加载失败');modal.remove();toast('done');};}async function addUrl(url){toast('start');try{const res = await fetch(url);const blob = await res.blob();if(blob.type.startsWith('video/')){const buf = await blob2buf(blob);const count = (await dbAllMedia()).length;if(count >= MAX){alert(`最多只能添加 ${MAX} 个媒体`);toast('done');return;}await dbAdd({ type: 'video' , mime: blob.type , data: buf , loop: true , lastUsed: 0 });const s = loadSettings();await apply(s);refreshPanel();toast('done');}else{const reader = new FileReader();reader.onload = e => startCropper(e.target.result);reader.readAsDataURL(blob);}}catch (e){alert('无法加载该 URL');toast('done');}}async function buildPanel(s){const pct = v => Math.round(v * 100);const allMedia = await dbAllMedia();const cnt = allMedia.length;let list = '';if(cnt){const items = allMedia.map(m => {const url = media2url(m);if(m.type === 'image'){return `<div class="bg-image-item" data-id="${m.id}"><img src="${url}"><button class="delete-btn" data-delete="${m.id}">×</button></div>`;}const loop = m.loop !== false ? '🔁' : '▶';return `<div class="bg-image-item" data-id="${m.id}"><div class="video-icon">🎥</div><button class="delete-btn" data-delete="${m.id}">×</button><button class="loop-toggle" data-loop="${m.id}">${loop}</button></div>`;});list = items.join('');}return `<h3> 背景设置</h3><div class="section-title"> 媒体管理 (${cnt}/${MAX})</div><div style="display:flex;gap:6px;margin-bottom:6px;"><input type="url" id="bg-url-input" placeholder="输入图片/视频URL" style="flex:1;"><button class="bg-upload-btn" id="bg-add-url">+</button><button class="bg-upload-btn" id="bg-upload-file">📁</button></div><div class="bg-image-list" id="bg-image-list">${list || '<span style="font-size:12px;color:#999;">暂无媒体</span>'}</div><div class="section-title collapsed" id="toggle-settings"> 图片设置 <span class="arrow">▼</span></div><div class="settings-block collapsed" id="settings-block"><div class="slider-group"><label>模糊度</label><input type="range" id="blur-slider" min="0" max="40" value="${Math.round(s.blur)}" step="1"><span class="val-display" id="blur-val">${Math.round(s.blur)}px</span></div><div class="slider-group"><label>亮度</label><input type="range" id="brightness-slider" min="30" max="200" value="${pct(s.bgBrightness)}" step="5"><span class="val-display" id="brightness-val">${pct(s.bgBrightness)}%</span></div><div class="slider-group"><label>饱和度</label><input type="range" id="saturation-slider" min="0" max="200" value="${pct(s.bgSaturation)}" step="5"><span class="val-display" id="saturation-val">${pct(s.bgSaturation)}%</span></div></div><div class="section-title collapsed" id="toggle-transparency"> 区域透明度 <span class="arrow">▼</span></div><div class="settings-block collapsed" id="transparency-block"><div class="slider-group"><label>导航栏</label><input type="range" id="nav-opacity-slider" min="0" max="100" value="${pct(s.navOpacity)}" step="1"><span class="val-display" id="nav-opacity-val">${pct(s.navOpacity)}%</span></div><div class="slider-group"><label>卡片</label><input type="range" id="card-opacity-slider" min="0" max="100" value="${pct(s.cardOpacity)}" step="1"><span class="val-display" id="card-opacity-val">${pct(s.cardOpacity)}%</span></div><div class="slider-group"><label>底部区域</label><input type="range" id="footer-opacity-slider" min="0" max="100" value="${pct(s.footerOpacity)}" step="1"><span class="val-display" id="footer-opacity-val">${pct(s.footerOpacity)}%</span></div></div><div class="section-title" style="cursor:default;"><span> 专栏全透</span><label style="display:flex;align-items:center;"><input type="checkbox" id="article-transparent-check" ${s.articleTransparent ? 'checked' : ''}></label></div><div class="section-title" style="cursor:default;"><span> 毛玻璃效果</span><label style="display:flex;align-items:center;"><input type="checkbox" id="global-glass-check" ${s.globalGlass ? 'checked' : ''}></label></div><div class="section-title" style="cursor:default;"><span> 随机背景</span><label style="display:flex;align-items:center;"><input type="checkbox" id="random-bg-check" ${s.randomBg ? 'checked' : ''}></label></div><div class="btn-row"><button class="btn-reset" id="btn-reset"> 恢复默认</button><button class="btn-clearall" id="btn-clearall"> 清空全部</button></div><button class="btn-close" id="btn-close-panel">✕ 关闭</button>`;}async function refreshPanel(){const list = document.getElementById('bg-image-list');if(!list)return;const allMedia = await dbAllMedia();if(!allMedia.length){list.innerHTML = '<span style="font-size:12px;color:#999;">暂无媒体</span>';return;}list.innerHTML = allMedia.map(m => {const url = media2url(m);if(m.type === 'image'){return `<div class="bg-image-item" data-id="${m.id}"><img src="${url}"><button class="delete-btn" data-delete="${m.id}">×</button></div>`;}const loop = m.loop !== false ? '🔁' : '▶';return `<div class="bg-image-item" data-id="${m.id}"><div class="video-icon">🎥</div><button class="delete-btn" data-delete="${m.id}">×</button><button class="loop-toggle" data-loop="${m.id}">${loop}</button></div>`;}).join('');list.querySelectorAll('.bg-image-item').forEach(item => {item.addEventListener('click' , async e => {if(e.target.closest('.delete-btn') || e.target.closest('.loop-toggle'))return;const id = item.dataset.id;const s = loadSettings();await setBackgroundById(id , s);});});list.querySelectorAll('.delete-btn').forEach(b => b.addEventListener('click' , async e => {e.stopPropagation();const id = b.dataset.delete;await dbDelete(id);const s = loadSettings();if(s.currentBgId == id)s.currentBgId = null;await apply(s);refreshPanel();}));list.querySelectorAll('.loop-toggle').forEach(b => b.addEventListener('click' , async e => {e.stopPropagation();const id = b.dataset.loop;const m = await dbGet(id);if(m?.type === 'video'){const newLoop = m.loop === false ? true : false;await dbUpdate(id , { loop: newLoop });b.textContent = newLoop ? '🔁' : '▶';}}));}function bindEvents(panel , settings , onChange){panel.querySelector('#bg-upload-file').addEventListener('click' , openFile);panel.querySelector('#bg-add-url').addEventListener('click' , () => {const url = panel.querySelector('#bg-url-input').value.trim();if(url){addUrl(url);panel.querySelector('#bg-url-input').value = '';}});const bindS = (id , vid , get , set , fmt) => {const s = panel.querySelector(id) , d = panel.querySelector(vid);if(!s || !d)return;const upd = () => {const v = get(s);set(settings , v);d.textContent = fmt(v);updateVars(settings);onChange(settings , false);};s.addEventListener('input' , upd , true);s.addEventListener('change' , upd , true);};bindS('#blur-slider' , '#blur-val' , s => parseInt(s.value) , (s , v) => s.blur = v , v => `${v}px`);bindS('#brightness-slider' , '#brightness-val' , s => parseInt(s.value) / 100 , (s , v) => s.bgBrightness = clamp(v , 0.3 , 2.0) , v => `${Math.round(v * 100)}%`);bindS('#saturation-slider' , '#saturation-val' , s => parseInt(s.value) / 100 , (s , v) => s.bgSaturation = clamp(v , 0 , 2.0) , v => `${Math.round(v * 100)}%`);bindS('#nav-opacity-slider' , '#nav-opacity-val' , s => parseInt(s.value) / 100 , (s , v) => s.navOpacity = clamp(v , 0 , 1) , v => `${Math.round(v * 100)}%`);bindS('#card-opacity-slider' , '#card-opacity-val' , s => parseInt(s.value) / 100 , (s , v) => s.cardOpacity = clamp(v , 0. , 1) , v => `${Math.round(v * 100)}%`);bindS('#footer-opacity-slider' , '#footer-opacity-val' , s => parseInt(s.value) / 100 , (s , v) => s.footerOpacity = clamp(v , 0 , 1) , v => `${Math.round(v * 100)}%`);const toggle1 = panel.querySelector('#toggle-settings') , block1 = panel.querySelector('#settings-block');toggle1.addEventListener('click' , () => {const c = toggle1.classList.toggle('collapsed');block1.classList.toggle('collapsed' , c);});const toggle2 = panel.querySelector('#toggle-transparency') , block2 = panel.querySelector('#transparency-block');toggle2.addEventListener('click' , () => {const c = toggle2.classList.toggle('collapsed');block2.classList.toggle('collapsed' , c);});const artCheck = panel.querySelector('#article-transparent-check');artCheck.addEventListener('change' , () => {settings.articleTransparent = artCheck.checked;onChange(settings);saveSettings(settings);});const glassCheck = panel.querySelector('#global-glass-check');glassCheck.addEventListener('change' , () => {settings.globalGlass = glassCheck.checked;onChange(settings);saveSettings(settings);});const randomCheck = panel.querySelector('#random-bg-check');randomCheck.addEventListener('change' , () => {settings.randomBg = randomCheck.checked;onChange(settings);saveSettings(settings);});panel.querySelector('#btn-reset').addEventListener('click' , async () => {await dbClear();Object.assign(settings , DEFAULTS);onChange(settings);saveSettings(settings);refreshPanel();refreshUI(panel , settings);});panel.querySelector('#btn-clearall').addEventListener('click' , async () => {if (confirm('确定清空所有媒体?')) {await dbClear();onChange(settings);saveSettings(settings);refreshPanel();refreshUI(panel , settings);await apply(settings);}});panel.querySelector('#btn-close-panel').addEventListener('click' , () => {settings.panelCollapsed = true;panel.classList.add('collapsed');saveSettings(settings);});}function refreshUI(panel , s) {const setV = (id , val) => {const el = panel.querySelector(id);if(el)el.value = Math.round(val);};setV('#blur-slider' , s.blur);setV('#brightness-slider' , s.bgBrightness * 100);setV('#saturation-slider' , s.bgSaturation * 100);setV('#nav-opacity-slider' , s.navOpacity * 100);setV('#card-opacity-slider' , s.cardOpacity * 100);setV('#footer-opacity-slider' , s.footerOpacity * 100);panel.querySelector('#blur-val').textContent = s.blur + 'px';panel.querySelector('#brightness-val').textContent = Math.round(s.bgBrightness * 100) + '%';panel.querySelector('#saturation-val').textContent = Math.round(s.bgSaturation * 100) + '%';panel.querySelector('#nav-opacity-val').textContent = Math.round(s.navOpacity * 100) + '%';panel.querySelector('#card-opacity-val').textContent = Math.round(s.cardOpacity * 100) + '%';panel.querySelector('#footer-opacity-val').textContent = Math.round(s.footerOpacity * 100) + '%';const artCheck = panel.querySelector('#article-transparent-check');if(artCheck)artCheck.checked = s.articleTransparent;const glassCheck = panel.querySelector('#global-glass-check');if(glassCheck)glassCheck.checked = s.globalGlass;const randomCheck = panel.querySelector('#random-bg-check');if(randomCheck)randomCheck.checked = s.randomBg;}function menu(){if(IS_GOJ || document.documentElement.classList.contains('lgb-columba')){if(!document.getElementById('luogu-bg-toggle')){const button = document.createElement('button');button.id = 'luogu-bg-toggle';button.type = 'button';button.textContent = '背景设置';button.addEventListener('click' , showPanel);document.body.appendChild(button);}return;}const side = document.querySelector('nav.sidebar.lside');if(side){const grp = [...side.querySelectorAll('.nav-group')].find(g => g.querySelector('.group-title .title')?.textContent.includes('更多功能'));if(grp){const ul = grp.querySelector('ul') , ref = [...ul.children].find(li => li.textContent.includes('图片上传'));if(ref && !ul.querySelector('[data-bg-custom-menu]')){const li = ref.cloneNode(true);li.setAttribute('data-bg-custom-menu' , 'true');li.querySelector('.title.minor').textContent = '背景设置';const a = li.querySelector('a');a.removeAttribute('href');a.addEventListener('click' , e => {e.preventDefault();showPanel();});ul.insertBefore(li , ref);}}}else{const old = document.querySelector('nav.lfe-body');if(old){const apps = old.querySelector('.popup-wrap .popup .apps');const ref = apps?.querySelector('a[href="/ticket"]');if(ref && !apps.querySelector('[data-bg-custom-menu-old]')){const a = ref.cloneNode(true);a.setAttribute('data-bg-custom-menu-old' , 'true');a.removeAttribute('href');a.textContent = '背景设置';a.addEventListener('click' , e => {e.preventDefault();showPanel();});ref.insertAdjacentElement('afterend' , a);}}}}function showPanel(){const p = document.getElementById('luogu-bg-panel');if(!p)return;p.classList.remove('collapsed');const s = loadSettings();s.panelCollapsed = false;saveSettings(s);}async function init(){injectStyles();if(!IS_GOJ && document.querySelector('script[src*="/columba/loader."]')){document.documentElement.classList.add('lgb-columba');injectArticleStyles();}if(IS_GOJ){document.documentElement.classList.add('lgb-goj');injectGojStyles();}const s = loadSettings();createLayer();await apply(s);const panel = await createPanel(s , async (upd , reload = true) => {if(!reload)upd.currentBgId = GM_getValue(SETTING_PREFIX + 'currentBgId' , upd.currentBgId);saveSettings(upd);await apply(upd , reload);});menu();new MutationObserver(menu).observe(document.body , { childList: true , subtree: true });new MutationObserver(async () => {if(!document.getElementById('luogu-bg-layer')){createLayer();await apply(loadSettings());}updateGlassOverlay(loadSettings());clearArticleBackground();updateSurfaces(loadSettings());}).observe(document.body , { childList: true , subtree: true });}async function createPanel(settings , onChange){const old = document.getElementById('luogu-bg-panel');if(old)old.remove();const panel = document.createElement('div');panel.id = 'luogu-bg-panel';if(settings.panelCollapsed)panel.classList.add('collapsed');panel.innerHTML = await buildPanel(settings);document.body.appendChild(panel);bindEvents(panel , settings , onChange);await refreshPanel();return panel;}if(document.readyState === 'loading'){document.addEventListener('DOMContentLoaded' , init);}else{init();}})();```::::::info[code]```js// ==UserScript==// @name 洛谷 IDE 代码全量统计 (注入底层版)// @namespace http://tampermonkey.net/// @version 2.0// @description 通过获取 CodeMirror 内部状态实现 100% 全量统计// @author Air// @match https://www.luogu.com.cn/problem/*// @grant none// @run-at document-start// ==/UserScript==(function() {'use strict';let lastByteCount = -1;const encoder = new TextEncoder();// 创建 UI 元素const sizeSpan = document.createElement('span');sizeSpan.id = 'luogu-code-size-display';sizeSpan.style.cssText = `margin: 0 15px;padding: 2px 10px;background: #f8f9fa;border-radius: 4px;color: #007bff;font-family: 'Consolas', monospace;font-size: 12px;border: 1px solid #007bff44;display: none;white-space: nowrap;font-weight: bold;`;// 核心函数:获取编辑器内的全量文本function getFullCode() {// 方案 A: 尝试通过 CodeMirror 6 的 DOM 引用获取内部 stateconst cmElement = document.querySelector('.cm-editor');if (cmElement && cmElement.view) {return cmElement.view.state.doc.toString();}// 方案 B: 洛谷某些版本可能会将内容挂载在特定的全局变量或特定的 contenteditable// 如果 A 失败,回退到通过特定属性查找const content = document.querySelector('.cm-content');if (content && content.cmView && content.cmView.view) {return content.cmView.view.state.doc.toString();}// 方案 C: 暴力保底方案 (如果上述都失效,则合并所有可能的文本块)// 注意:这种方案在极长代码下仍可能受限,但比直接 textContent 稳健return content?.textContent || "";}function refresh() {if (!window.location.hash.includes('#ide')) return;// UI 挂载const toolbar = document.querySelector('.ide-toolbar');const actions = document.querySelector('.ide-toolbar .actions');if (toolbar && actions && !document.getElementById('luogu-code-size-display')) {toolbar.insertBefore(sizeSpan, actions);sizeSpan.style.display = 'inline-block';}const code = getFullCode();if (code) {const bytes = encoder.encode(code).length;if (bytes !== lastByteCount) {lastByteCount = bytes;const kb = (bytes / 1024).toFixed(2);sizeSpan.innerHTML = `Size: ${bytes} B | ${kb} KB`;}}}// 处理洛谷这种动态加载的 SPA// 采用高频检查方案,因为 CodeMirror 的 view 实例是异步挂载到 DOM 上的setInterval(refresh, 1000);// 监听输入,确保打字时数字会动document.addEventListener('input', (e) => {if (e.target.closest('.cm-content')) {refresh();}}, true);})();```::::::info[复制 Markdown]```js// ==UserScript==// @name 洛谷专栏 Markdown 源码// @namespace https://www.luogu.com.cn/// @version 1.1.0// @description 从当前专栏页面复制原始 Markdown// @match https://www.luogu.com.cn/article/*// @match https://www.luogu.com/article/*// @run-at document-idle// @noframes// @grant GM_setClipboard// ==/UserScript==(() => {'use strict';const route = /^\/article\/([a-z0-9]+)\/?$/i;const label = '复制 MD';if (!route.test(location.pathname)) return;function copy(txt) {const ctx = document.getElementById('lentille-context');let art;try {art = JSON.parse(ctx?.textContent ?? 'null')?.data?.article;} catch {alert('页面内嵌数据解析失败。');return;}if (typeof art?.content !== 'string') {alert('当前页面未提供 Markdown 源码。');return;}if (art.lid !== location.pathname.match(route)?.[1]) {alert('文章地址已切换,请刷新当前页面后再复制。');return;}GM_setClipboard(art.content, 'text', () => {txt.textContent = '已复制';setTimeout(() => { txt.textContent = label; }, 1500);});}function mount() {if (!route.test(location.pathname)) return;for (const bar of document.querySelectorAll('.article-content > .actions')) {if (bar.querySelector('.luogu-copy-md')) continue;const ref = [...bar.children].find(el => el.matches('.button-2line') && el.querySelector('.text')?.textContent.trim() === '不推荐');if (!ref) continue;const btn = document.createElement('button');btn.type = 'button';btn.className = 'button-2line luogu-copy-md';btn.style.cssText = 'border:0;background:none;padding:0;font:inherit;align-items:center;white-space:nowrap';const icon = document.createElement('span');icon.className = 'icon';icon.textContent = '⎘';icon.setAttribute('aria-hidden', 'true');const txt = ref.querySelector('.text').cloneNode(false);txt.textContent = label;for (const attr of txt.getAttributeNames().filter(name => name.startsWith('data-v-'))) {btn.setAttribute(attr, '');icon.setAttribute(attr, '');}btn.append(icon, txt);btn.addEventListener('click', () => copy(txt));ref.after(btn);}}new MutationObserver(mount).observe(document.body, {childList: true, subtree: true});mount();})();```::::::info[anti-ai]```js// ==UserScript==// @name Luogu 反隐藏内容高亮显示// @namespace http://tampermonkey.net/// @version 1.0// @description 显示并高亮洛谷讨论区中被隐藏的内容(class="invisible")// @author You// @match https://www.luogu.com.cn/discuss/*// @match https://www.luogu.com.cn/*// @grant GM_addStyle// @run-at document-start// ==/UserScript==(function() {'use strict';// 注入CSS样式 - 覆盖原有的invisible样式GM_addStyle(`/* 覆盖洛谷的隐藏样式 */.lfe-marked .invisible,.invisible {position: static !important;opacity: 1 !important;pointer-events: auto !important;-webkit-user-select: text !important;user-select: text !important;/* 高亮显示 */background-color: #ffeb3b !important; /* 黄色背景 */color: #000 !important; /* 黑色文字 */text-decoration: none !important; /* 移除可能的装饰 */display: inline !important; /* 确保内联显示 */}/* 为了确保在各种背景下都能看清 */.am-article .invisible,.lg-article .invisible,.marked .invisible,.lfe-body .invisible {position: static !important;opacity: 1 !important;background-color: #ffeb3b !important;color: #000 !important;}`);})();```::::::info[3]放烟花。```js// ==UserScript==// @name Firework Confetti Click & Drag Effect// @namespace http://tampermonkey.net/// @version 1.5.0// @description 按下聚合上升,释放绚丽爆开!支持点击与拖动持续发射,带重力与双色系切换。// @author Gemini_Modified// @match *://*/*// @grant none// ==/UserScript==(function() {'use strict';function fireworkEffect() {let rockets = []; // 存储上升的烟花弹let pieces = []; // 存储爆开的碎屑let cvs, ctx, w, h;// 状态控制let isMouseDown = false;let lastFireTime = 0;const fireInterval = 0; // 拖动发射间隔(毫秒),数值越小越密集const colorThemes = {bluePurple: ["#1E90FF", "#8A2BE2", "#9370DB", "#00BFFF", "#4B0082", "#7B68EE"],redOrange: ["#FF4500", "#FF1493", "#FFD700", "#FF6347", "#DC143C", "#FFA500"]};const GRAVITY = 0.15;const FRICTION = 0.96;cvs = document.createElement("canvas");document.body.appendChild(cvs);cvs.setAttribute("style", "width: 100%; height: 100%; top: 0; left: 0; z-index: 99999; position: fixed; pointer-events: none;");if (cvs.getContext && window.addEventListener) {ctx = cvs.getContext("2d");updateCvsSize();window.addEventListener('resize', updateCvsSize, false);// 核心发射逻辑const spawnRocket = (x, y) => {const now = Date.now();// 只有当时间间隔超过阈值才发射,防止移动过快导致性能问题if (now - lastFireTime > fireInterval) {const themeKey = Math.random() > 0 ? 'bluePurple' : 'redOrange';rockets.push(new Rocket(x, y, colorThemes[themeKey]));lastFireTime = now;}};// 监听按下window.addEventListener("mousedown", (e) => {isMouseDown = true;spawnRocket(e.clientX, e.clientY);}, false);// 监听移动window.addEventListener("mousemove", (e) => {if (isMouseDown) {spawnRocket(e.clientX, e.clientY);}}, false);// 监听释放window.addEventListener("mouseup", () => {isMouseDown = false;}, false);// 监听焦点丢失(防止切屏导致无限发射)window.addEventListener("blur", () => {isMouseDown = false;}, false);requestAnimationFrame(loop);}function updateCvsSize() {cvs.width = window.innerWidth * 2;cvs.height = window.innerHeight * 2;cvs.style.width = window.innerWidth + 'px';cvs.style.height = window.innerHeight + 'px';ctx.scale(2, 2);w = window.innerWidth;h = window.innerHeight;}// --- 第一阶段:上升的烟花弹 ---class Rocket {constructor(x, y, palette) {this.x = x;this.y = y;this.palette = palette;this.vy = -12; // 初始向上速度this.vx = (Math.random() - 0.5) * 4; // 稍微增加横向偏移感this.alive = true;this.targetY = y - (Math.random() * 300 + 300)*1; // 爆炸高度}update() {this.x += this.vx;this.y += this.vy;if (this.y <= this.targetY || this.vy > -1) {this.explode();this.alive = false;}}explode() {for (let i = 0; i < 200; i++) { // 减少单次碎屑数量以提升拖动时的性能pieces.push(new Confetti(this.x, this.y, this.palette));}}draw() {ctx.save();ctx.beginPath();ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);ctx.fillStyle = this.palette[0];ctx.shadowBlur = 15;ctx.shadowColor = this.palette[0];ctx.fill();ctx.restore();}}// --- 第二阶段:爆开的碎屑 ---class Confetti {constructor(x, y, palette) {this.x = x;this.y = y;const angle = Math.random() * Math.PI * 2;const force = (Math.random() * 15 + 0.1) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9) * (Math.random() * 0.1 + 0.9);this.vx = Math.cos(angle) * force;this.vy = Math.sin(angle) * force;this.size = Math.random() * 2 + 2;this.color = palette[Math.floor(Math.random() * palette.length)];this.opacity = 1;this.fade = Math.random() * 0.015 + 0.015;this.rotation = Math.random() * 360;this.rotSpeed = (Math.random() - 0.5) * 20;this.scaleY = 1;}update() {this.vx *= FRICTION;this.vy *= FRICTION;this.vy += GRAVITY;this.x += this.vx;this.y += this.vy;this.rotation += this.rotSpeed;this.scaleY = Math.cos(Date.now() * 0.01 + this.x * 0.5);this.opacity -= this.fade;}draw() {if (this.opacity <= 0) return;ctx.save();ctx.translate(this.x, this.y);ctx.rotate(this.rotation * Math.PI / 180);ctx.scale(1, this.scaleY);ctx.globalAlpha = this.opacity;ctx.fillStyle = this.color;ctx.fillRect(-this.size, -this.size / 2, this.size * 2, this.size);ctx.restore();}}function loop() {ctx.clearRect(0, 0, w, h);for (let i = rockets.length - 1; i >= 0; i--) {rockets[i].update();if (rockets[i].alive) rockets[i].draw();else rockets.splice(i, 1);}for (let i = pieces.length - 1; i >= 0; i--) {pieces[i].update();pieces[i].draw();if (pieces[i].opacity <= 0 || pieces[i].y > h) {pieces.splice(i, 1);}}requestAnimationFrame(loop);}}fireworkEffect();})();```::::::info[背景]https://www.luogu.com.cn/paste/9jb9zd4e::::::info[跳转]```js// ==UserScript==// @name 洛谷网页跳转// @namespace http://tampermonkey.net/// @version 2026-08-03// @description jump jump jump jump jump jump jump jump jump jump jump jump jump jump jump jump pmuj pmuj pmuj pmuj pmuj pmju pmuj pmuj pmuj pmuj pmuj// @author You// @match https://*/*// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==// @grant none// ==/UserScript==(function() {'use strict';const host = location.host;const pathname = location.pathname;// 规则 1:访问 https://www.luogu.com/problem/solution/* 跳转到 .com.cnif (host === 'www.luogu.com' && pathname.startsWith('/problem/solution/')) {location.replace(location.href.replace('www.luogu.com', 'www.luogu.com.cn'));return;}// 规则 3:访问 https://www.luogu.com (仅根目录/首页)跳转到 .com.cnif (host === 'www.luogu.com' && (pathname === '/' || pathname === '')) {location.replace('https://www.luogu.com.cn' + location.search + location.hash);return;}// 规则 2:访问 https://www.luogu.com.cn/article/* 且页面标题包含“安全访问中心”时跳转到 .comif (host === 'www.luogu.com.cn' && pathname.startsWith('/article/')) {const checkAndRedirect = () => {if (document.title && document.title.includes('安全访问中心')) {location.replace(location.href.replace('www.luogu.com.cn', 'www.luogu.com'));}};// 立即尝试检测一次checkAndRedirect();// DOM 加载完成后检测一次if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', checkAndRedirect);}// 监听 <title> 的动态变化(适应 SPA 或防御页面异步修改标题)const observer = new MutationObserver(() => checkAndRedirect());observer.observe(document, { subtree: true, childList: true, characterData: true });}// 规则 2:访问 https://www.luogu.com.cn/article/* 且页面标题包含“安全访问中心”时跳转到 .comif (host === 'www.luogu.com.cn' && pathname.startsWith('/paste/')) {const checkAndRedirect = () => {if (document.title && document.title.includes('安全访问中心')) {location.replace(location.href.replace('www.luogu.com.cn', 'www.luogu.com'));}};// 立即尝试检测一次checkAndRedirect();// DOM 加载完成后检测一次if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', checkAndRedirect);}// 监听 <title> 的动态变化(适应 SPA 或防御页面异步修改标题)const observer = new MutationObserver(() => checkAndRedirect());observer.observe(document, { subtree: true, childList: true, characterData: true });}})();```::::::info[验证码]```js// ==UserScript==// @name 洛谷验证码自动识别并填写 (优化版)// @namespace https://github.com/mayoi-Akira// @version 0.2.1// @description 使用卷积神经网络训练的验证码识别模型,自动识别填写洛谷提交时的验证码// @match *://www.luogu.com.cn/*// @icon https://www.luogu.com.cn/favicon.ico// @grant GM_xmlhttpRequest// @author Akira// @license MIT// ==/UserScript==(() => {const server = "http://8.130.64.15:3636";const canvas = document.createElement("canvas");const ctx = canvas.getContext("2d");function recognize(img, callback) {canvas.width = img.naturalWidth;canvas.height = img.naturalHeight;ctx.drawImage(img, 0, 0);const data = canvas.toDataURL("image/jpeg").split(",")[1];GM_xmlhttpRequest({method: "POST",url: server,headers: { "Content-Type": "application/json" },data: JSON.stringify({ image: data }),onload: (resp) => {try {const { prediction } = JSON.parse(resp.responseText);callback(prediction);} catch (e) {console.error("OCR 获取失败", e);callback("");}},onerror: (err) => {console.error("OCR 请求失败", err);callback("");},timeout: 5000,});}const handleImage = (img) => {// 检查是否正在识别或已识别当前 src,避免高频/重复发包if (img.dataset.ocrSrc === img.src || img.dataset.ocrProcessing === "true") {return;}const input = document.querySelector('input[placeholder*="验证码"]');if (!input) {console.warn("未找到输入框");return;}// 设置状态锁img.dataset.ocrProcessing = "true";const run = () => {recognize(img, (text) => {// 标记该 src 已成功识别img.dataset.ocrSrc = img.src;delete img.dataset.ocrProcessing;if (text) {input.value = text;input.dispatchEvent(new Event("input", { bubbles: true }));input.dispatchEvent(new Event("change", { bubbles: true }));}});};if (img.complete && img.naturalWidth > 0) {run();} else {img.onload = run;}};const observer = new MutationObserver((mutations) => {for (const m of mutations) {if (m.type === "childList") {m.addedNodes.forEach((node) => {if (node.nodeType === Node.ELEMENT_NODE) {if (node.nodeName === "IMG" && node.src && node.src.includes("captcha")) {handleImage(node);}const imgs = node.querySelectorAll('img[src*="captcha"]');imgs.forEach(handleImage);}});} else if (m.type === "attributes" &&m.target.nodeName === "IMG" &&m.target.src.includes("captcha")) {handleImage(m.target);}}});const root = document.querySelector("#captcha-container") || document.body;// 关键优化:指定 attributeFilter 为 ['src'],仅在图片地址更新时触发observer.observe(root, {childList: true,subtree: true,attributes: true,attributeFilter: ["src"]});const existingImg = document.querySelector('img[src*="captcha"]');if (existingImg) {handleImage(existingImg);}})();```::::::info[题目颜色]```js// ==UserScript==// @name 洛谷题目难度着色+标签速览// @namespace https://www.luogu.com.cn/// @version 2.3// @description 自动着色洛谷题目编号,悬停显示标签,双击跳转题目;// @author Assistant// @match https://www.luogu.com.cn/*// @grant GM_xmlhttpRequest// @grant GM_getValue// @grant GM_setValue// @grant GM_openInTab// @connect cdn.luogu.com.cn// @require https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js// ==/UserScript==(function() {'use strict';// 难度颜色映射const DIFFICULTY_COLORS = {0: '#808080', // 灰色1: '#e74c3c', // 红色2: '#e67e22', // 橙色3: '#f1c40f', // 黄色4: '#2ecc71', // 绿色5: '#00bcd4', // 青色6: '#2196F3', // 蓝色7: '#9c3dcf', // 紫色8: '#000000' // 黑色};const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';const DB_NAME = 'LuoguProblemDB';const DB_VERSION = 1;const STORE_NAME = 'problems';const MIN_UPDATE_INTERVAL = 3 * 24 * 60 * 60 * 1000; // 3天// 题目编号正则,支持 P, B, CF, SP, AT, UVA 等const PID_PATTERN = /\b(?:P|B|CF|SP|AT(?:_[A-Za-z0-9]+)?|UVA)\d+[A-Za-z0-9]*\b/g;let problemDataMap = new Map(); // pid -> { difficulty, title, tags, type }let processedTextNodes = new WeakSet();let observer = null;let tooltip = null;function createTooltip() {if (tooltip) return;tooltip = document.createElement('div');tooltip.id = 'luogu-problem-tooltip';tooltip.style.cssText = `position: fixed;z-index: 9999999;background: rgba(30, 30, 30, 0.95);color: #fff;padding: 8px 12px;border-radius: 6px;font-size: 12px;max-width: 300px;word-wrap: break-word;pointer-events: none;display: none;box-shadow: 0 2px 8px rgba(0,0,0,0.3);`;document.body.appendChild(tooltip);}function showTooltip(x, y, content) {createTooltip();tooltip.innerHTML = content;tooltip.style.display = 'block';const rect = tooltip.getBoundingClientRect();let left = x + 10;let top = y + 10;if (left + rect.width > window.innerWidth - 5) left = x - rect.width - 10;if (top + rect.height > window.innerHeight - 5) top = y - rect.height - 10;tooltip.style.left = left + 'px';tooltip.style.top = top + 'px';}function hideTooltip() {if (tooltip) tooltip.style.display = 'none';}function showStatusMessage(text, isError = false) {const existing = document.getElementById('luogu-problem-status');if (existing) existing.remove();const div = document.createElement('div');div.id = 'luogu-problem-status';div.style.cssText = `position: fixed; top: 20px; right: 20px;background: ${isError ? '#f44336' : '#2196F3'};color: white; padding: 8px 16px;border-radius: 6px; z-index: 999999;font-size: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);max-width: 300px; word-wrap: break-word;`;div.textContent = text;document.body.appendChild(div);if (!isError) {setTimeout(() => { if (div.parentNode) div.remove(); }, 5000);}}function openDB() {return new Promise((resolve, reject) => {const request = indexedDB.open(DB_NAME, DB_VERSION);request.onupgradeneeded = (e) => {const db = e.target.result;if (!db.objectStoreNames.contains(STORE_NAME)) {db.createObjectStore(STORE_NAME, { keyPath: 'pid' });}};request.onsuccess = () => resolve(request.result);request.onerror = () => reject(request.error);});}async function getProblemCount() {const db = await openDB();return new Promise((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readonly');const store = tx.objectStore(STORE_NAME);const req = store.count();req.onsuccess = () => resolve(req.result);req.onerror = () => reject(req.error);});}async function clearProblems() {const db = await openDB();return new Promise((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);const req = store.clear();req.onsuccess = () => resolve();req.onerror = () => reject(req.error);});}async function bulkInsert(problems) {const db = await openDB();return new Promise((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readwrite');const store = tx.objectStore(STORE_NAME);for (const p of problems) {store.put(p);}tx.oncomplete = () => resolve();tx.onerror = () => reject(tx.error);});}async function loadProblemDataMap() {const db = await openDB();return new Promise((resolve, reject) => {const tx = db.transaction(STORE_NAME, 'readonly');const store = tx.objectStore(STORE_NAME);const req = store.getAll();req.onsuccess = () => {const map = new Map();req.result.forEach(item => {map.set(item.pid, {difficulty: item.difficulty,title: item.title || '',tags: item.tags || [],type: item.type || ''});});resolve(map);};req.onerror = () => reject(req.error);});}async function downloadAndStoreData(onProgress) {if (typeof pako === 'undefined') {throw new Error('pako 库未加载,请刷新页面重试。');}await clearProblems();return new Promise((resolve, reject) => {GM_xmlhttpRequest({method: 'GET',url: DATA_URL,responseType: 'arraybuffer',onload: async (res) => {try {const compressed = new Uint8Array(res.response);const decompressed = pako.ungzip(compressed, { to: 'string' });const lines = decompressed.split('\n').filter(line => line.trim() !== '');const total = lines.length;const batchSize = 1000;let imported = 0;const importBatch = async (start) => {const end = Math.min(start + batchSize, total);const batch = [];for (let i = start; i < end; i++) {try {const obj = JSON.parse(lines[i]);batch.push({pid: obj.pid,title: obj.title,difficulty: obj.difficulty,type: obj.type,tags: obj.tags || []});} catch (e) {}}if (batch.length > 0) {await bulkInsert(batch);imported += batch.length;if (onProgress) onProgress(imported, total);}if (end < total) {await importBatch(end);} else {resolve();}};await importBatch(0);} catch (e) {reject(e);}},onerror: (err) => reject(err)});});}function openProblemPage(pid) {const url = `https://www.luogu.com.cn/problem/${pid}`;if (typeof GM_openInTab === 'function') {GM_openInTab(url, { active: true, insert: true });} else {window.open(url, '_blank');}}function colorizeNode(node) {if (!node) return;if (node.nodeType === Node.TEXT_NODE) {processTextNode(node);} else if (node.nodeType === Node.ELEMENT_NODE) {if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE' || node.tagName === 'NOSCRIPT') return;if (node.classList && node.classList.contains('lg-diff-color')) return;const childNodes = node.childNodes;for (let i = 0; i < childNodes.length; i++) {colorizeNode(childNodes[i]);}}}function processTextNode(node) {if (processedTextNodes.has(node)) return;let parent = node.parentNode;while (parent && parent !== document.body) {if (parent.tagName === 'A' && parent.getAttribute('href')?.includes('/problem/')) {return;}parent = parent.parentNode;}const text = node.textContent;if (!text) return;PID_PATTERN.lastIndex = 0;const replacements = [];let match;while ((match = PID_PATTERN.exec(text)) !== null) {const pid = match[0];const problemData = problemDataMap.get(pid);if (problemData) {replacements.push({start: match.index,end: PID_PATTERN.lastIndex,pid: pid,difficulty: problemData.difficulty,tags: problemData.tags,title: problemData.title});}}if (replacements.length === 0) {processedTextNodes.add(node);return;}const fragment = document.createDocumentFragment();let lastIndex = 0;for (const r of replacements) {if (r.start > lastIndex) {fragment.appendChild(document.createTextNode(text.substring(lastIndex, r.start)));}const span = document.createElement('span');span.className = 'lg-diff-color';span.style.color = DIFFICULTY_COLORS[r.difficulty] || '#808080';span.style.fontWeight = 'bold';span.textContent = r.pid;span.style.cursor = 'pointer';span.addEventListener('mouseenter', (e) => {const tags = r.tags && r.tags.length ? r.tags.join(', ') : '暂无标签';const title = r.title ? `<strong>${r.pid} ${r.title}</strong>` : `<strong>${r.pid}</strong>`;showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`);});span.addEventListener('mousemove', (e) => {if (tooltip && tooltip.style.display === 'block') {showTooltip(e.clientX, e.clientY, tooltip.innerHTML);}});span.addEventListener('mouseleave', hideTooltip);span.addEventListener('dblclick', (e) => {e.preventDefault();e.stopImmediatePropagation();openProblemPage(r.pid);});fragment.appendChild(span);lastIndex = r.end;}if (lastIndex < text.length) {fragment.appendChild(document.createTextNode(text.substring(lastIndex)));}node.parentNode.replaceChild(fragment, node);processedTextNodes.add(node);}function colorizeExistingDOM() {colorizeNode(document.body);}function startObserver() {if (observer) observer.disconnect();observer = new MutationObserver((mutations) => {mutations.forEach((mutation) => {mutation.addedNodes.forEach((node) => {colorizeNode(node);});});});observer.observe(document.body, { childList: true, subtree: true });}//初始化async function init() {try {const lastUpdate = GM_getValue('last_update_time', 0);const now = Date.now();let count = await getProblemCount();if (count === 0) {showStatusMessage('正在下载洛谷题库数据,首次使用可能需要几十秒...');console.log('[洛谷题目着色] 无本地题库,开始下载...');await downloadAndStoreData((current, total) => {if (current % 5000 === 0 || current === total) {showStatusMessage(`题库下载中: ${current}/${total}`);}});GM_setValue('last_update_time', Date.now());showStatusMessage('题库下载完成,正在着色...');console.log('[洛谷题目着色] 下载完成');} else if (now - lastUpdate >= MIN_UPDATE_INTERVAL) {showStatusMessage('题库数据已超过3天未更新,正在更新...');console.log('[洛谷题目着色] 超过3天,开始更新题库...');await downloadAndStoreData((current, total) => {if (current % 5000 === 0 || current === total) {showStatusMessage(`题库更新中: ${current}/${total}`);}});GM_setValue('last_update_time', Date.now());showStatusMessage('题库更新完成,正在着色...');} else {console.log('[洛谷题目着色] 题库数据在3天内已更新过,使用本地缓存');}problemDataMap = await loadProblemDataMap();console.log(`[洛谷题目着色] 已加载 ${problemDataMap.size} 条题目数据`);colorizeExistingDOM();startObserver();} catch (err) {console.error('[洛谷题目着色] 初始化失败:', err);showStatusMessage('题库下载失败,请检查网络后刷新重试', true);startObserver();}}if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', init);} else {init();}})();```:::::::::::success[工具]:::info[文本加密&解密]```cpp#include<bits/stdc++.h>#include<immintrin.h>#pragma GCC target("avx2")#include<ext/pb_ds/assoc_container.hpp>#include<ext/pb_ds/tree_policy.hpp>46 行未改动#define putchar(x) ((p3==ob+BS&&(fwrite(ob,p3-ob,1,stdout),p3=ob),*p3++=x))#endif#define isd(c) (c>47&&c<58)#define iss(c) (c<33)//#define cin io//#define cout iotemplate<typename T>inline bool read(T&s){s=0;int w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))s=s*10+c-48,c=getchar();return s*=w,1;}inline bool read(char&s){while(s=getchar(),iss(s));return s!=EOF;}inline bool read(char*s){char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))*s++=c,c=getchar();return *s=0,1;}inline bool read(std::string&s){s="";char c;while(c=getchar(),iss(c));if(c==EOF)return 0;while(!iss(c))s+=c,c=getchar();return 1;}template<typename T>inline bool read_f(T&x){x=0;T w=1;char c;while(c=getchar(),!isd(c)&&c!=EOF)if(c=='-')w=-1;if(c==EOF)return 0;while(isd(c))x=x*10+(c^48),c=getchar();if(c=='.'){T f=0,k=1;while(c=getchar(),isd(c))f=f*10+(c^48),k*=10;x+=f/k;}x*=w;return 1;}inline bool read(float&x){return read_f(x);}inline bool read(double&x){return read_f(x);}inline bool read(long double&x){return read_f(x);}template<size_t N>inline bool read(std::bitset<N>&b){b.reset();char c;while(c=getchar(),c!='0'&&c!='1'&&c!=EOF);if(c==EOF)return 0;static char buf[N+5];int i=0;do{buf[i++]=c;c=getchar();}while((c=='0'||c=='1')&&i<N);For(j,0,i-1)if(buf[j]=='1')b[i-1-j]=1;return 1;}template<typename T>inline void write(T x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+48);}inline void write(char x){putchar(x);}inline void write(char*x){while(*x)putchar(*x++);}inline void write(const char*x){for(int i=0;x[i];i++)putchar(x[i]);}inline void write(std::string x){for(char c:x)putchar(c);}template<typename T>inline void write(T x,int k){if(x<0)putchar('-'),x=-x;T e=0.5;For(i,1,k)e/=10;x+=e;ull n=(ull)x;write(n);if(k>0){putchar('.');x-=n;For(i,1,k){x*=10;int c=(int)x;putchar(c+48);x-=c;}}}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(float x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(long double x){write(x,6);}[[deprecated("Float detected: use write(x,k) for precision control")]]inline void write(double x){write(x,6);}template<size_t N>inline void write(std::bitset<N>b){write(b.to_string());}struct F{bool s=1;inline void flush(){fwrite(ob,p3-ob,1,stdout);p3=ob;}~F(){flush();}explicit operator bool()const{return s;}}io;template<typename T>inline F&operator>>(F&i,T&b){i.s=read(b);return i;}template<typename T>inline F&operator<<(F&i,T b){write(b);return i;}}using namespace fast_IO;template<typename T> using Set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;template<typename T,typename TT> using Map=gp_hash_table<T,TT>;void freopen(string name="test",int type=1,string aaa="",string bbb=""){if(type==1){freopen((name+".in").c_str(),"r",stdin),freopen((name+".out").c_str(),"w",stdout);}else if(type==2){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"w",stdout);}else if(type==3){freopen((name+aaa).c_str(),"r",stdin),freopen((name+bbb).c_str(),"wb",stdout);}else if(type==4){freopen((name+aaa).c_str(),"wb",stdout);}else{return;}}class Timer{private:ull GetCycleCount(){unsigned hi,lo;__asm__ volatile("rdtsc":"=a"(lo),"=d"(hi));return ((ull)(hi)<<32)|lo;}ull startCycle,startTime;public:void restart(){startCycle=GetCycleCount();startTime=chrono::steady_clock::now().time_since_epoch().count();}ull getCycles(){return GetCycleCount()-startCycle;}double getTime(){return (chrono::steady_clock::now().time_since_epoch().count()-startTime)/1e6;}}timer;class Random{private:mt19937 randGen{random_device{}()};public:int randint(int l,int r){uniform_int_distribution<int> randDis(l,r);return randDis(randGen);}double frand(double l,double r){uniform_real_distribution<double> randDis(l,r); return randDis(randGen);}}Rand;ll gcd(ll aa,ll bb){ll a=aa,b=bb;if(!a||!b)return a|b;ll shift=__builtin_ctzll(a|b);a>>=__builtin_ctzll(a);while(b){b>>=__builtin_ctzll(b);if(a>b)swap(a,b);b-=a;}return a<<shift;}Int gcd(Int aa,Int bb){Int a=aa,b=bb;if(!a||!b)return a|b;Int shift=__builtin_ctz(a|b);a>>=__builtin_ctz(a);while(b){b>>=__builtin_ctz(b);if(a>b)swap(a,b);b-=a;}return a<<shift;}constexpr Int N=5e5+5,MOD=998244353;#if __cplusplus > 201703Lnamespace Radix{int c[65536];template<typename T>void run(T* a,int n){static T t[N];T *x=a,*y=t,m=(T)1<<(sizeof(T)*8-1);For(i,0,n-1)x[i]^=m;for(int p=0;p<(int)sizeof(T)*8;p+=16){ms(c);For(i,0,n-1)c[(x[i]>>p)&0xFFFF]++;For(i,1,65535)c[i]+=c[i-1];Fro(i,n-1,0)y[--c[(x[i]>>p)&0xFFFF]]=x[i];swap(x,y);}if(x!=a)For(i,0,n-1)a[i]=x[i];For(i,0,n-1)a[i]^=m;}}template<typename T,typename Cmp=std::less<T>>void Sort(T* st,T* ed,Cmp cmp=Cmp()){int n=ed-st;if(n<2)Happy;if(n<131072||!is_integral_v<T>||!is_same_v<Cmp,std::less<T>>){sort(st,ed,cmp);Happy;}Radix::run(st,n);}#endifstruct SimpleBlockCipher{static ull hsh(string s){ull h=0xcbf29ce484222325;for(char c:s)h^=(ull)c,h*=0x100000001b3;return h;}static ull nxt(ull&s){return s=s*6364136223846793005ULL+1442695040888963407ULL;}static ull rol(ull v,int s){return(v<<s)|(v>>(64-s));}static vector<ull> enc(string t,string k){vector<ull> res;ull s=hsh(k);int len=t.length();for(int i=0;i<len;i+=8){ull b=0;char buf[8]={0};memcpy(buf,t.data()+i,min(8LL,len-i));memcpy(&b,buf,8);b^=nxt(s);b=rol(b,13);res.pb(b);}return res;}static ull ror(ull v,int s){return(v>>s)|(v<<(64-s));}static string dec(const vector<ull>&c,const string&k){string res="";ull s=hsh(k);for(ull b:c){ull msk=nxt(s);b=ror(b,13);b^=msk;char buf[8];memcpy(buf,&b,8);For(i,0,7)res+=buf[i];}size_t p=res.find_last_not_of('\0');return(p!=string::npos)?res.substr(0,p+1):"";}};string s,k,tmp;void encrypt(){freopen("encoded.txt","w",stdout);while(getline(cin,tmp))s+=tmp+'\n';if(!s.empty()&&s.back()=='\n')s.pop_back();int p=s.find_last_of('\n');if(p!=string::npos)k=s.substr(p+1),s=s.substr(0,p);vector<ull> res=SimpleBlockCipher::enc(s,k);for(ull v:res)cout<<v<<" ";}void decrypt(){vector<ull> encoded;cin>>k;freopen("encoded.txt","r",stdin);freopen("decoded.txt","w",stdout);ull awa=0;while(cin>>awa)encoded.pb(awa);cout<<SimpleBlockCipher::dec(encoded,k)<<'\n';}Int main(){timer.restart();decrypt();Happy Ending;}```:::::::