跳到正文

算法·理论

模板大全

zhchz约 39 分钟
原文
文章信息与版本

文章信息

发布
2025年11月9日
收录
2026年2月8日
更新
2026年11月14日
篇幅
约 39 分钟

版本

  1. v2当前
  2. v1

Tools

随机数生成

C++
#include<chrono>
#define randint uniform_int_distribution<int>
#define randll uniform_int_distribution<long long>
mt19937 genint(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 genll(chrono::steady_clock::now().time_since_epoch().count());

//Usage
randint(from,to)(genint);
randll(from,to)(genll);

运行时间测量

C++
// Recommended
auto start = chrono::high_resolution_clock::now();
// Work
auto stop = chrono::high_resolution_clock::now();
int usetime = chrono::duration_cast<chrono::milliseconds>(stop-start).count();

// Bad
int start = clock();
// Work
int stop = clock();
int usetime = stop - start;

对拍

C++
#include<bits/stdc++.h>
#include<chrono>
#include<climits>
#include<windows.h>
typedef long long ll;
typedef unsigned long long ull;
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;

signed main(){
	int cnt=0;
	while(1){
		system("gen > data.in");
		system("std < data.in > std.out");
		auto start = chrono::high_resolution_clock::now();
		system("my < data.in > my.out");
		auto stop = chrono::high_resolution_clock::now();
		int usetime = chrono::duration_cast<chrono::milliseconds>(stop-start).count();
		if(system("fc/W std.out my.out")){
			cout<<"WA time: "<<usetime<<" ms."<<endl;
			system("pause");
			break;
		}else{
			cout<<"#"<<cnt<<" AC time: "<<usetime<<" ms."<<endl;
		}
	}
	return 0;
}

Other

IO优化

C++
namespace io{const int __SIZE=(1<<21)+1;char ibuf[__SIZE],*iS,*iT,obuf[__SIZE],*oS=obuf,*oT=oS+__SIZE-1,__c,qu[55];int __f,qr,_eof;
#define Gc()(iS==iT?(iT=(iS=ibuf)+fread(ibuf,1,__SIZE,stdin),(iS==iT?EOF:*iS++)):*iS++)
inline void flush(){fwrite(obuf,1,oS-obuf,stdout),oS=obuf;}inline void gc(char&x){x=Gc();}inline void pc(char x){*oS++=x;if(oS==oT)flush();}inline void pstr(const char*s){int __len=strlen(s);for(__f=0;__f<__len;++__f)pc(s[__f]);}inline void gstr(char*s){for(__c=Gc();__c<32||__c>126||__c==' ';)__c=Gc();for(;__c>31&&__c<127&&__c!=' '&&__c!='\n'&&__c!='\r';++s,__c=Gc())*s=__c;*s=0;}template<class I>inline bool gi(I&x){_eof=0;for(__f=1,__c=Gc();(__c<'0'||__c>'9')&&!_eof;__c=Gc()){if(__c=='-')__f=-1;_eof|=__c==EOF;}for(x=0;__c<='9'&&__c>='0'&&!_eof;__c=Gc())x=x*10+(__c&15),_eof|=__c==EOF;x*=__f;return!_eof;}template<class I>inline void print(I x){if(!x)pc('0');if(x<0)pc('-'),x=-x;while(x)qu[++qr]=x%10+'0',x/=10;while(qr)pc(qu[qr--]);}struct Flusher_{~Flusher_(){flush();}}io_flusher_;}using io::pc;using io::gc;using io::pstr;using io::gstr;using io::gi;using io::print;
Raw
C++
namespace io {
	const int __SIZE = (1 << 21) + 1;
	char ibuf[__SIZE], *iS, *iT, obuf[__SIZE], *oS = obuf, *oT = oS + __SIZE - 1, __c, qu[55]; int __f, qr, _eof;
	#define Gc() (iS == iT ? (iT = (iS = ibuf) + fread (ibuf, 1, __SIZE, stdin), (iS == iT ? EOF : *iS ++)) : *iS ++)
	inline void flush () { fwrite (obuf, 1, oS - obuf, stdout), oS = obuf; }
	inline void gc (char &x) { x = Gc(); }
	inline void pc (char x) { *oS ++ = x; if (oS == oT) flush (); }
	inline void pstr (const char *s) { int __len = strlen(s); for (__f = 0; __f < __len; ++__f) pc (s[__f]); }
	inline void gstr (char *s) { for(__c = Gc(); __c < 32 || __c > 126 || __c == ' ';)  __c = Gc();
		for(; __c > 31 && __c < 127 && __c != ' ' && __c != '\n' && __c != '\r'; ++s, __c = Gc()) *s = __c; *s = 0; }
	template <class I> inline bool gi (I &x) { _eof = 0;
		for (__f = 1, __c = Gc(); (__c < '0' || __c > '9') && !_eof; __c = Gc()) { if (__c == '-') __f = -1; _eof |= __c == EOF; }
		for (x = 0; __c <= '9' && __c >= '0' && !_eof; __c = Gc()) x = x * 10 + (__c & 15), _eof |= __c == EOF; x *= __f; return !_eof; }
	template <class I> inline void print (I x) { if (!x) pc ('0'); if (x < 0) pc ('-'), x = -x;
		while (x) qu[++ qr] = x % 10 + '0',  x /= 10; while (qr) pc (qu[qr --]); }
	struct Flusher_ {~Flusher_(){flush();}}io_flusher_;
} using io::pc; using io::gc; using io::pstr; using io::gstr; using io::gi; using io::print;

用法:

使用 gi(x); 读入一个任意的整型 x 等价于 scanf("%d", &x);其中可以将 %d 自动识别为对应类型。

使用 print(x); 输出一个任意的整型 x 等价于 printf("%d", x);其中可以将 %d 自动识别为对应类型。

使用 gc(c); 读入一个字符 c 等价于 scanf("%c", &c)

使用 pc(c); 输出一个字符 c 等价于 putchar(c);

使用 gstr(str); 读入一个字符串 str 等价于 scanf("%s", str);

使用 pstr(str); 输出一个字符串 str 等价于 printf("%s", str);

Debug

C++
template<typename T>ostream&operator<<(ostream&os,const vector<T>&v){os<<"{ ";string sep;for(const auto&x:v)os<<sep<<x,sep=", ";return os<<" }";}
template<typename T,size_t size>ostream&operator<<(ostream&os,const array<T,size>&arr){os<<"{ ";string sep;for(const auto&x:arr)os<<sep<<x,sep=", ";return os<<" }";}
template<typename A,typename B>ostream&operator<<(ostream&os,const pair<A,B>&p){return os<<'('<<p.first<<","<<p.second<<')';}
template<typename K,typename V>ostream&operator<<(ostream&os,const map<K,V>&m){os<<"{ ";string sep;for(const auto&p:m)os<<sep<<p.first<<":"<<p.second,sep=", ";return os<<" }";}
template<typename T>ostream&operator<<(ostream&os,const set<T>&s){os<<"{ ";string sep;for(const auto&x:s)os<<sep<<x,sep=", ";return os<<" }";}
namespace detail{template<typename T>constexpr bool is_string_type_v=std::is_same_v<std::decay_t<T>,std::string>||std::is_same_v<std::decay_t<T>,const char*>||std::is_same_v<std::decay_t<T>,char*>;template<typename T>void print_val(const T&val){if constexpr(is_string_type_v<T>){std::cerr<<'"'<<val<<'"';}else{std::cerr<<val;}}inline std::string_view trim(std::string_view sv){sv.remove_prefix(std::min(sv.find_first_not_of(" \t"),sv.size()));size_t end=sv.find_last_not_of(" \t");if(end!=std::string_view::npos){sv.remove_suffix(sv.size()-end-1);}return sv;}template<typename...Args>void dbgg_impl(int line,const char*msg,const char*raw_names,Args&&...args){std::cerr<<"Line "<<line<<": "<<msg;if constexpr(sizeof...(Args)>0){if(strlen(msg)>0)std::cerr<<" | ";std::string_view names(raw_names);size_t arg_idx=0;([&]{if(arg_idx>0)std::cerr<<", ";size_t comma_pos=names.find(',');std::string_view current_name=(comma_pos==std::string_view::npos)?names:names.substr(0,comma_pos);std::cerr<<trim(current_name)<<"=";print_val(args);if(comma_pos!=std::string_view::npos){names.remove_prefix(comma_pos+1);}arg_idx++;}(),...);}std::cerr<<std::endl;}}
#ifdef LOCAL_ZCZ
#define dbg(Msg,...)detail::dbgg_impl(__LINE__,Msg,#__VA_ARGS__,##__VA_ARGS__)
#else
#define dbg(...)
#endif
Raw
C++
// 重载ostream运算符,支持容器打印
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
	os << '{';
	std::string sep;
	for (const auto& x : v) os << sep << x, sep = ",";
	return os << '}';
}

template <typename T, size_t size>
std::ostream& operator<<(std::ostream& os, const std::array<T, size>& arr) {
	os << '{';
	std::string sep;
	for (const auto& x : arr) os << sep << x, sep = ",";
	return os << '}';
}

template <typename A, typename B>
std::ostream& operator<<(std::ostream& os, const std::pair<A, B>& p) {
	return os << '(' << p.first << "," << p.second << ')';
}

// 支持std::map
template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::map<K, V>& m) {
	os << '{';
	std::string sep;
	for (const auto& p : m) os << sep << p.first << ":" << p.second, sep = ",";
	return os << '}';
}

// 支持std::set
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& s) {
	os << '{';
	std::string sep;
	for (const auto& x : s) os << sep << x, sep = ",";
	return os << '}';
}


#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>
#include <cstring>

namespace detail {
	
	// 判断类型是否需要加引号 (std::string 或 C风格字符串)
	template <typename T>
	constexpr bool is_string_type_v = 
	std::is_same_v<std::decay_t<T>, std::string> || 
	std::is_same_v<std::decay_t<T>, const char*> || 
	std::is_same_v<std::decay_t<T>, char*>;
	
	// 打印值的辅助函数
	template <typename T>
	void print_val(const T& val) {
		if constexpr (is_string_type_v<T>) {
			std::cerr << '"' << val << '"';
		} else {
			std::cerr << val;
		}
	}
	
	// 去除字符串视图首尾的空白字符
	inline std::string_view trim(std::string_view sv) {
		sv.remove_prefix(std::min(sv.find_first_not_of(" \t"), sv.size()));
		size_t end = sv.find_last_not_of(" \t");
		if (end != std::string_view::npos) {
			sv.remove_suffix(sv.size() - end - 1);
		}
		return sv;
	}
	
	// 核心打印函数
	template <typename... Args>
	void dbgg_impl(int line, const char* msg, const char* raw_names, Args&&... args) {
		std::cerr << "Line " << line << ": " << msg;
		
		// 如果有参数,打印分隔符
		if constexpr (sizeof...(Args) > 0) {
			
			if(strlen(msg)>0) std::cerr << " | ";
			
			std::string_view names(raw_names);
			size_t arg_idx = 0;
			
			// 使用 C++17 折叠表达式 (Fold Expression) 遍历参数
			([&] {
				// 1. 打印参数间的分隔符
				if (arg_idx > 0) std::cerr << ", ";
				
				// 2. 解析当前参数名
				size_t comma_pos = names.find(',');
				std::string_view current_name = (comma_pos == std::string_view::npos) 
				? names 
				: names.substr(0, comma_pos);
				
				std::cerr << trim(current_name) << "=";
				
				// 3. 打印参数值(根据类型决定是否加引号)
				print_val(args);
				
				// 4. 移动到下一个参数名
				if (comma_pos != std::string_view::npos) {
					names.remove_prefix(comma_pos + 1);
				}
				arg_idx++;
			}(), ...); // 折叠展开
		}
		
		std::cerr << std::endl;
	}
}

// ========== 宏定义 ==========
#ifdef LOCAL_ZCZ
// ##__VA_ARGS__ 用于处理 args 为空的情况 (GCC/Clang扩展,但在C++20前是处理空参数的常用技巧)
#define dbg(Msg, ...) \
detail::dbgg_impl(__LINE__, Msg, #__VA_ARGS__, ##__VA_ARGS__)
#else
#define dbg(...)
#endif

要求 C++14,支持 vector、array、pair、map、set。

二分

最简单的闭区间写法。

C++
while(l<=r){
	int mid=(l+r)>>1;
	if(check(mid)){
		ans=mid;
		l=mid+1;
	}else{
		r=mid-1;
	}
}
其他写法

第一个模板是尽量往左找目标,第二个模板是尽量往右找目标。

C++
while(l<r){
	int mid=l+r>>1;
	if(check(mid)) r=mid;
	else l=mid+1;
}
/*
0 0 ... 0 1 ... 1 1
          ^
*/
while(l<r){
	int mid=l+r+1>>1;
	if(check(mid)) l=mid;
	else r=mid-1;
}
/*
1 1 ... 1 0 ... 0 0
        ^
*/

并查集

猜猜为什么会有这个?

C++
void init(){
	for(int i=1;i<=n;i++)
		fa[i]=i;
}

int find(int x){
	return fa[x]==x?x:fa[x]=find(fa[x]);
}

void merge(int x,int y){
	fa[find(x)]=find(y);
}

数据结构

树状数组

C++
struct BIT{
	int t[N];
#define lowbit(x) ((x)&(-(x)))
	void clear(){memset(t,0,sizeof t);}
	void add(int x,int v){
		while(x<=n){
			t[x]+=v;
			x+=lowbit(x);
		}
	}
	int getsum(int x){
		int res=0;
		while(x){
			res+=t[x];
			x-=lowbit(x);
		}
		return res;
	}
	int query(int l,int r){
		l=max(0ll,l);
		r=min(r,n);
		if(r<l) return 0;
		return getsum(r)-getsum(l-1);
	}
	void change(int x,int v){
		add(x,v-query(x,x));
	}
};

线段树

普通

C++
#define ll long long
#define lc (x<<1)
#define rc (x<<1|1)
#define mid ((l+r)>>1)

typedef ll Ttype;
struct data{
	Ttype sum,add;
}tree[N*8];

void pushup(int x){
	tree[x].sum=tree[lc].sum+tree[rc].sum;
}

void build(int x,int l,int r){
	if(l==r) tree[x].sum=a[l];
	else{
		build(lc,l,mid);
		build(rc,mid+1,r);
		pushup(x);
	}
}

void pushdown(int x,int l,int r){
	tree[lc].add+=tree[x].add;
	tree[rc].add+=tree[x].add;
	tree[lc].sum+=tree[x].add*(mid-l+1);
	tree[rc].sum+=tree[x].add*(r-mid);
	tree[x].add=0;
}

void add(int x,int l,int r,int from,int to,Ttype v){
	if(l>=from && r<=to){
		tree[x].add+=v,tree[x].sum+=v*(r-l+1);
		return;
	}
	pushdown(x,l,r);
	if(from<=mid) add(lc,l,mid,from,to,v);
	if(to>mid) add(rc,mid+1,r,from,to,v);
	pushup(x);
}

Ttype query(int x,int l,int r,int from,int to){
	if(l>=from && r<=to) return tree[x].sum;
	pushdown(x,l,r);
	ll ans=0;
	if(from<=mid) ans+=query(lc,l,mid,from,to);
	if(to>mid) ans+=query(rc,mid+1,r,from,to);
	return ans;
}

Plus

C++
#define lc (x<<1)
#define rc (x<<1|1)
#define mid (l+r>>1)

const int N=100010;
int n,m,a[N],len[N<<2],tag1[N<<2],tag2[N<<2];

struct T{//只存数据,不存Tag
	int w,b,wl,wr,wm,bl,br,bm;
	T(){w=b=wl=wr=wm=bl=br=bm=0;}
	T(int w,int b,int wl,int wr,int wm,int bl,int br,int bm):
	w(w),b(b),wl(wl),wr(wr),wm(wm),bl(bl),br(br),bm(bm){}
}t[N<<2];

T hb(T a,T b){//合并两个区间
	return T(
		a.w+b.w, a.b+b.b,
		a.b?a.wl:a.wl+b.wl, b.b?b.wr:b.wr+a.wr,
		max(max(a.wm,b.wm),a.wr+b.wl),
		a.w?a.bl:a.bl+b.bl, b.w?b.br:b.br+a.br,
		max(max(a.bm,b.bm),a.br+b.bl)
	);
}

void P(int x,int opr){//对t[x]做opr的操作,即更新数据并打上标记
	if(opr==0){
		tag1[x]=0;tag2[x]=0;
		t[x]=T(0,len[x],0,0,0,len[x],len[x],len[x]);
	}
	if(opr==1){
		tag1[x]=1;tag2[x]=0;
		t[x]=T(len[x],0,len[x],len[x],len[x],0,0,0);
	}
	if(opr==2){
		tag2[x]^=1;
		t[x]=T(t[x].b,t[x].w,t[x].bl,t[x].br,t[x].bm,t[x].wl,t[x].wr,t[x].wm);
	}
}

void pushdown(int x){
	if(tag1[x]!=-1) P(lc,tag1[x]),P(rc,tag1[x]);//先处理赋值(如果有)
	if(tag2[x]) P(lc,2),P(rc,2);//再处理取反(如果有)
	tag1[x]=-1,tag2[x]=0;//取消标记
}

void build(int x,int l,int r){
	len[x]=r-l+1,tag1[x]=-1;
	if(l==r){
		t[x]=T(a[l],a[l]^1,a[l],a[l],a[l],a[l]^1,a[l]^1,a[l]^1);
		return;
	}
	build(lc,l,mid);
	build(rc,mid+1,r);
	t[x]=hb(t[lc],t[rc]);//pushup
}

void change(int x,int l,int r,int from,int to,int opr){
	if(r<from || l>to) return;//递归查询无需if,在此判断
	if(from<=l && r<=to){
		P(x,opr);//直接操作
		return;
	}
	pushdown(x);
	change(lc,l,mid,from,to,opr);
	change(rc,mid+1,r,from,to,opr);
	t[x]=hb(t[lc],t[rc]);
	return;
}

T query(int x,int l,int r,int from,int to){
	if(r<from || l>to) return T();
	if(from<=l && r<=to){
		return t[x];
	}
	pushdown(x);
	return hb(query(lc,l,mid,from,to),query(rc,mid+1,r,from,to));
}

signed main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	build(1,1,n);
    int qql,qqr,opp;
	while(m--){
		scanf("%d%d%d",&opp,&qql,&qqr);
		qql++,qqr++;
		if(opp<=2){
			change(1,1,n,qql,qqr,opp);
		}else{
			T que=query(1,1,n,qql,qqr);
			printf("%d\n",opp==3?que.w:que.wm);
		}
//        cout<<"Tree: ";
//        for(int k=1;k<=n;k++){
//            cout<<query(1,1,n,k,k).w;printf(" ");
//        }cout<<"\n";
	}
	return 0;
}

OD Tree

C++
struct node{
	int l,r;
	mutable int col;
	node(int l,int r,int col):l(l),r(r),col(col){}
	node()=default;
	const bool operator<(const node oth)const{
		return l<oth.l;
	}
	friend ostream&operator<<(ostream& os,const node& n){
		os<<"("<<n.l<<","<<n.r<<","<<n.col<<")";
		return os;
	}
};
set<node>st;
auto split(int x){
	auto it=st.lower_bound({x,0,0});
	if(it!=st.end() && it->l==x)return it;
	it--;
	int l=it->l,r=it->r,col=it->col;
	st.erase(it);
	st.insert({l,x-1,col});
	return st.insert(node(x,r,col)).fi;
}
void setcol(int from,int to,int c){
	auto itr=split(to+1),itl=split(from);
	st.erase(itl,itr);
	st.insert({from,to,c});
}

树

倍增LCA

C++
#define fi first
#define se second

const int N=500010;
int n,m,k,s,q,x,y;
int dep[N],f[20][N],lg[N];
vector<int> edge[N];

void dfs(int x,int fa){
	f[0][x]=fa;dep[x]=dep[fa]+1;
	for(int i=1;i<=lg[dep[x]];i++)
		f[i][x]=f[i-1][f[x][i-1]];
	for(int y:edge[x])
		if(y!=fa) dfs(y,x);
}

int lca(int x,int y){
	if(dep[x]<dep[y]) swap(x,y);
	for(int k=18;k>=0;k--)
		if(dep[f[k][x]]>=dep[y])
			x=f[k][x];
	if(x==y) return x;
	for(int k=18;k>=0;k--)
		if(f[k][x]!=f[k][y])
			x=f[k][x],y=f[k][y];
	return f[0][x];
}

signed main(){
	cin>>n>>m>>s;
	lg[0]=-1;
	for(int i=1;i<=n;i++)
		lg[i]=lg[i>>1]+1;
	for(int i=1;i<n;i++){
		cin>>x>>y;
		edge[x].push_back(y);
		edge[y].push_back(x);
	}
	dep[s]=1;
	dfs(s,0);
	for(int i=1;i<=m;i++){
		cin>>x>>y;
		cout<<lca(x,y)<<"\n"; 
	}
}

DFN 求 LCA

C++
int fa[N],d[30][N],dfn[N],tot=0;
void dfs(int x,int f){
	dfn[x]=++tot;
	fa[x]=d[0][dfn[x]]=f;
	for(int v:edge[x]) if(v!=f) dfs(v,x);
}
int get(int x,int y){return dfn[x]<dfn[y]?x:y;}
int lca(int x,int y){
	if(x==y) return x;
	x=dfn[x],y=dfn[y];
	if(x>y) swap(x,y);
	int t=__lg(y-x++);
	return get(d[t][x],d[t][y-(1<<t)+1]);
}
// Init
dfs(rt,0);
for(int i=1;i<=__lg(n);i++)
	for(int j=1;j+(1<<i)-1<=n;j++)
		d[i][j]=get(d[i-1][j],d[i-1][j+(1<<i-1)]);

链剖

LCA

C++
#define ll long long

const int N=500010;
int n,m,x,y,rt;
int size[N],f[N],dep[N],son[N],top[N];
vector<int> edge[N];

void dfs1(int x,int fa){
	f[x]=fa;size[x]=1;
	dep[x]=dep[fa]+1;
	for(int y:edge[x]){
		if(y==fa) continue;
		dfs1(y,x);
		size[x]+=size[y];
		if(size[y]>size[son[x]])
			son[x]=y;
	}
}

void dfs2(int x,int tp){
	top[x]=tp;
	if(son[x]) dfs2(son[x],tp);
	for(int y:edge[x]){
		if(y==f[x]||y==son[x]) continue;
		dfs2(y,y);
	}
}

int lca(int x,int y){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		x=f[top[x]];
	}
	return dep[x]>dep[y]?y:x;
}

int main(){
	cin>>n>>m>>rt;
	for(int i=1;i<n;i++){
		cin>>x>>y;
		edge[x].push_back(y);
		edge[y].push_back(x);
	}
	dfs1(rt,0);
	dfs2(rt,rt);
	while(m--){
		cin>>x>>y;
		cout<<lca(x,y)<<"\n";
	}
}

模版题

C++
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<string.h>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define ll long long
#define lc (x<<1)
#define rc (x<<1|1)
#define mid ((l+r)>>1)

const int N=500010;
int n,m,x,y,z,rt,tot=0,mod,op;
int size[N],f[N],dep[N],son[N],top[N],id[N],rev[N],w[N];
vector<int> edge[N];

//////////////线段树///////////////

typedef int Ttype;
struct data{
	Ttype sum,add;
}tree[N*8];

void pushup(int x){
	tree[x].sum=tree[lc].sum+tree[rc].sum;
	tree[x].sum%=mod;
}

void build(int x,int l,int r){
	if(l==r) tree[x].sum=w[rev[l]]%mod;
	else{
		build(lc,l,mid);
		build(rc,mid+1,r);
		pushup(x);
	}
}

void pushdown(int x,int l,int r){
	tree[lc].add+=tree[x].add;
    tree[rc].add+=tree[x].add;
	tree[lc].sum+=tree[x].add*(mid-l+1);
    tree[rc].sum+=tree[x].add*(r-mid);
	tree[x].add=0;
	tree[lc].sum%=mod;tree[rc].sum%=mod;
	tree[lc].add%=mod;tree[rc].add%=mod;
}

void add(int x,int l,int r,int from,int to,Ttype v){
	if(l>=from && r<=to){
		tree[x].add+=v,tree[x].sum+=v*(r-l+1);
		tree[x].add%=mod,tree[x].sum%=mod;
		return;
	}
	pushdown(x,l,r);
	if(from<=mid) add(lc,l,mid,from,to,v);
	if(to>mid) add(rc,mid+1,r,from,to,v);
	pushup(x);
}

Ttype query(int x,int l,int r,int from,int to){
	if(l>=from && r<=to) return tree[x].sum;
	pushdown(x,l,r);
	ll ans=0;
	if(from<=mid) ans+=query(lc,l,mid,from,to);
	if(to>mid) ans+=query(rc,mid+1,r,from,to);
	return ans%mod;
}

///////////////////////////////////

void dfs1(int x,int fa){
	f[x]=fa;size[x]=1;
	dep[x]=dep[fa]+1;
	for(int y:edge[x]){
		if(y==fa) continue;
		dfs1(y,x);
		size[x]+=size[y];
		if(size[y]>size[son[x]])
			son[x]=y;
	}
}

void dfs2(int x,int tp){
	top[x]=tp;
	id[x]=++tot;
	rev[tot]=x;
	if(son[x]) dfs2(son[x],tp);
	for(int y:edge[x]){
		if(y==f[x]||y==son[x]) continue;
		dfs2(y,y);
	}
}

void Pth_add(int x,int y,int z){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		add(1,1,n,id[top[x]],id[x],z);
		x=f[top[x]];
	}
	if(dep[x]>dep[y])
		swap(x,y);
	add(1,1,n,id[x],id[y],z);
}

int Pth_qy(int x,int y){
	int ans=0;
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		ans+=query(1,1,n,id[top[x]],id[x]);
		ans%=mod;
		x=f[top[x]];
	}
	if(dep[x]>dep[y])
		swap(x,y);
	ans+=query(1,1,n,id[x],id[y]);
	return ans%mod;
}

void Son_add(int x,int z){
	add(1,1,n,id[x],id[x]+size[x]-1,z);
} 

int Son_qy(int x){
	return query(1,1,n,id[x],id[x]+size[x]-1)%mod;
}

int main(){
	cin>>n>>m>>rt>>mod;
	for(int i=1;i<=n;i++) cin>>w[i];
	for(int i=1;i<n;i++){
		cin>>x>>y;
		edge[x].push_back(y);
		edge[y].push_back(x);
	}
	dfs1(rt,0);
	dfs2(rt,rt);
	build(1,1,n);
	while(m--){
		cin>>op;
		if(op==1){
			cin>>x>>y>>z;
			Pth_add(x,y,z);
		}else if(op==2){
			cin>>x>>y;
			cout<<Pth_qy(x,y)<<"\n";
		}else if(op==3){
			cin>>x>>z;
			Son_add(x,z);
		}else{
			cin>>x;
			cout<<Son_qy(x)<<"\n";
		}
	}
}
原文