跳到正文

个人记录

军火库说是

NegetiveEdgeWeight约 118 分钟
原文

这是 2026年10月17日 存档的第 14 版,不是当前版本。查看当前版本

文章信息与版本

主要是自用。需要的可以自取。

缺省源
编译选项
代码
-std=c++26 -Wall -Wextra -Wl,-stack=536870912 -Wshadow -O2 -static
交互题编译选项
代码
g++ grader.cpp [your_implemention] -o [your_implemention] -std=c++26 -Wall -Wextra -Wl,-stack=536870912 -Wshadow -O2 -static
缺省源
C++
#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
#endif
using 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;
}
除掉主函数的缺省源
C++
#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
#endif
using 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;
数据结构
文艺平衡树(1016B)

FHQ Treap。

C++
struct 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);
	else
		y=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);
}
普通平衡树(76B)
C++
tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update> st;
Weight Balanced Leafy Tree
C++
constexpr 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);
	}
}
线段树

WIP

树链剖分(3182B)
C++
vector<int> g[N];
int n,m,r
int 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 treeovo
struct 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 dis
void 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;
}
插件
code
JavaScript
// ==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 引用获取内部 state
        const 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);

})();
anti-ai
JavaScript
// ==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;
        }
    `);
})();
3

放烟花。

JavaScript
// ==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();
})();
背景
跳转
JavaScript
// ==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.cn
    if (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.cn
    if (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/* 且页面标题包含“安全访问中心”时跳转到 .com
    if (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/* 且页面标题包含“安全访问中心”时跳转到 .com
    if (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 });
    }
})();
验证码
JavaScript
// ==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);
  }
})();
题目颜色
JavaScript
// ==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();
    }
})();
工具
文本加密&解密
C++
#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>
#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=b;a<=c;a++)
#define Fro(a,b,c) for(int a=b;a>=c;a--)
#define ms(a) memset(a,0,sizeof a)
#define msinf(a) memset(a,0x3f,sizeof a)
#define Pii pair<int,int>
#define Inline __inline__
#define fi first
#define se second
#define y1 y1ovo
#define y2 y2ovo
#define j1 j1ovo
#define j2 j2ovo
#define mp make_pair
#define pb push_back
#define eb emplace_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 llld __float128
#define Ceil(a,b) ceil(1.0*a/b)
#define Floor(a,b) floor(1.0*a/b)
#define stdpq std::priority_queue
#define pbpq __gnu_pbds::priority_queue
#define Fopen(in) freopen(in".in","r",stdin);freopen(in".out","w",stdout);
#define Happy io.flush();
#define Ending return cerr<<"\nTime Used: "<<fixed<<setprecision(0)<<timer.getTime()<<" ms",0
#define LL
#ifdef LL
#define int long long
#define inf 0x3f3f3f3f3f3f3f3f
#else
#define inf 0x3f3f3f3f
#endif
using namespace std;using namespace __gnu_pbds;using namespace __gnu_cxx;
namespace 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 io
template<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 > 201703L
namespace 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);}
#endif
struct 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;
}