跳到正文

个人记录

数据结构大集合

OneZeroTree_Flipped约 59 分钟
原文
文章信息与版本

文章信息

收录
2026年2月18日
更新
2026年4月2日
篇幅
约 59 分钟

版本

  1. v3当前
  2. v2
  3. v1

最近太颓就逼自己做出所有数据结构的板子。

2.18

大整数类型BigInt
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdexcept>

class BigInt {
private:
    std::vector<int> digits;   // 低位在前,每个元素0-9
    bool isNegative;

    // 去除前导零,并处理零的符号
    void trim() {
        while (digits.size() > 1 && digits.back() == 0) {
            digits.pop_back();
        }
        if (digits.size() == 1 && digits[0] == 0) {
            isNegative = false;
        }
    }

    // 比较绝对值大小:返回1 if |this| > |other|, 0 if equal, -1 if less
    int absCompare(const BigInt& other) const {
        if (digits.size() != other.digits.size()) {
            return digits.size() > other.digits.size() ? 1 : -1;
        }
        for (int i = digits.size() - 1; i >= 0; --i) {
            if (digits[i] != other.digits[i]) {
                return digits[i] > other.digits[i] ? 1 : -1;
            }
        }
        return 0;
    }

    // 绝对值加法:|a| + |b|
    static BigInt absAdd(const BigInt& a, const BigInt& b) {
        BigInt result;
        result.isNegative = false;
        int carry = 0;
        size_t maxSize = std::max(a.digits.size(), b.digits.size());
        for (size_t i = 0; i < maxSize || carry; ++i) {
            int sum = carry;
            if (i < a.digits.size()) sum += a.digits[i];
            if (i < b.digits.size()) sum += b.digits[i];
            result.digits.push_back(sum % 10);
            carry = sum / 10;
        }
        return result;
    }

    // 绝对值减法:|a| - |b|,假设 |a| >= |b|
    static BigInt absSubtract(const BigInt& a, const BigInt& b) {
        BigInt result;
        result.isNegative = false;
        int borrow = 0;
        for (size_t i = 0; i < a.digits.size(); ++i) {
            int diff = a.digits[i] - borrow;
            if (i < b.digits.size()) diff -= b.digits[i];
            if (diff < 0) {
                diff += 10;
                borrow = 1;
            } else {
                borrow = 0;
            }
            result.digits.push_back(diff);
        }
        result.trim();
        return result;
    }

    // 绝对值乘法:|a| * |b|
    static BigInt absMultiply(const BigInt& a, const BigInt& b) {
        BigInt result;
        result.isNegative = false;
        result.digits.resize(a.digits.size() + b.digits.size(), 0);
        for (size_t i = 0; i < a.digits.size(); ++i) {
            int carry = 0;
            for (size_t j = 0; j < b.digits.size() || carry; ++j) {
                long long prod = result.digits[i + j] + carry;
                if (j < b.digits.size()) prod += (long long)a.digits[i] * b.digits[j];
                result.digits[i + j] = prod % 10;
                carry = prod / 10;
            }
        }
        result.trim();
        return result;
    }

    // ---------- 字符串辅助函数(用于除法)----------
    static std::string toStringAbs(const BigInt& num) {
        std::string s;
        for (int i = num.digits.size() - 1; i >= 0; --i) {
            s.push_back('0' + num.digits[i]);
        }
        return s.empty() ? "0" : s;
    }

    static int compareString(const std::string& a, const std::string& b) {
        if (a.length() != b.length()) return a.length() > b.length() ? 1 : -1;
        for (size_t i = 0; i < a.length(); ++i) {
            if (a[i] != b[i]) return a[i] > b[i] ? 1 : -1;
        }
        return 0;
    }

    static std::string multiplyString(const std::string& num, int digit) {
        if (digit == 0) return "0";
        std::string result;
        int carry = 0;
        for (int i = num.length() - 1; i >= 0; --i) {
            int prod = (num[i] - '0') * digit + carry;
            result.push_back('0' + prod % 10);
            carry = prod / 10;
        }
        if (carry) result.push_back('0' + carry);
        std::reverse(result.begin(), result.end());
        return result;
    }

    static std::string subtractString(const std::string& a, const std::string& b) {
        // 假设 a >= b
        std::string result;
        int borrow = 0;
        int i = a.length() - 1, j = b.length() - 1;
        while (i >= 0 || j >= 0) {
            int digitA = (i >= 0) ? (a[i] - '0') : 0;
            int digitB = (j >= 0) ? (b[j] - '0') : 0;
            int diff = digitA - digitB - borrow;
            if (diff < 0) {
                diff += 10;
                borrow = 1;
            } else {
                borrow = 0;
            }
            result.push_back('0' + diff);
            --i; --j;
        }
        // 去除前导零
        while (result.size() > 1 && result.back() == '0') {
            result.pop_back();
        }
        std::reverse(result.begin(), result.end());
        return result;
    }

    // 绝对值除法:计算商和余数,使用字符串长除法
    static void absDivide(const BigInt& dividend, const BigInt& divisor, BigInt& quotient, BigInt& remainder) {
        std::string dividendStr = toStringAbs(dividend);
        std::string divisorStr = toStringAbs(divisor);

        if (compareString(dividendStr, divisorStr) < 0) {
            quotient = BigInt(0);
            remainder = dividend;
            return;
        }

        std::string quotStr;
        std::string remStr;

        for (char ch : dividendStr) {
            remStr.push_back(ch);
            // 去除前导零,但保留至少一位
            size_t pos = remStr.find_first_not_of('0');
            if (pos != std::string::npos) {
                remStr = remStr.substr(pos);
            } else {
                remStr = "0";
            }

            if (compareString(remStr, divisorStr) >= 0) {
                int d = 0;
                for (int k = 9; k >= 0; --k) {
                    std::string prod = multiplyString(divisorStr, k);
                    if (compareString(prod, remStr) <= 0) {
                        d = k;
                        break;
                    }
                }
                quotStr.push_back('0' + d);
                std::string prod = multiplyString(divisorStr, d);
                remStr = subtractString(remStr, prod);
            } else {
                if (!quotStr.empty()) {
                    quotStr.push_back('0');
                }
            }
        }

        if (quotStr.empty()) quotStr = "0";
        // 去除商的前导零
        size_t pos = quotStr.find_first_not_of('0');
        if (pos != std::string::npos) {
            quotStr = quotStr.substr(pos);
        } else {
            quotStr = "0";
        }

        // 去除余数的前导零
        pos = remStr.find_first_not_of('0');
        if (pos != std::string::npos) {
            remStr = remStr.substr(pos);
        } else {
            remStr = "0";
        }

        quotient = BigInt(quotStr);
        remainder = BigInt(remStr);
    }

public:
    // 构造函数
    BigInt(long long num = 0) {
        isNegative = (num < 0);
        if (num < 0) num = -num;
        if (num == 0) {
            digits.push_back(0);
            isNegative = false;
        } else {
            while (num > 0) {
                digits.push_back(num % 10);
                num /= 10;
            }
        }
    }

    BigInt(const std::string& str) {
        isNegative = false;
        size_t start = 0;
        if (str[0] == '-') {
            isNegative = true;
            start = 1;
        }
        for (int i = str.length() - 1; i >= (int)start; --i) {
            digits.push_back(str[i] - '0');
        }
        trim();
    }

    // 输出
    friend std::ostream& operator<<(std::ostream& os, const BigInt& num) {
        if (num.isNegative && !(num.digits.size() == 1 && num.digits[0] == 0)) {
            os << '-';
        }
        for (int i = num.digits.size() - 1; i >= 0; --i) {
            os << num.digits[i];
        }
        return os;
    }

    // 比较运算符(可选)
    bool operator==(const BigInt& other) const {
        return isNegative == other.isNegative && digits == other.digits;
    }

    bool operator!=(const BigInt& other) const {
        return !(*this == other);
    }

    // 加法
    BigInt operator+(const BigInt& other) const {
        if (isNegative == other.isNegative) {
            BigInt result = absAdd(*this, other);
            result.isNegative = isNegative;
            return result;
        } else {
            int cmp = absCompare(other);
            if (cmp == 0) return BigInt(0);
            else if (cmp > 0) {
                BigInt result = absSubtract(*this, other);
                result.isNegative = isNegative;
                return result;
            } else {
                BigInt result = absSubtract(other, *this);
                result.isNegative = other.isNegative;
                return result;
            }
        }
    }

    // 减法:a - b = a + (-b)
    BigInt operator-(const BigInt& other) const {
        BigInt negOther = other;
        negOther.isNegative = !other.isNegative;
        return *this + negOther;
    }

    // 乘法
    BigInt operator*(const BigInt& other) const {
        BigInt result = absMultiply(*this, other);
        result.isNegative = (isNegative != other.isNegative);
        if (result.digits.size() == 1 && result.digits[0] == 0) {
            result.isNegative = false;
        }
        return result;
    }

    // 除法
    BigInt operator/(const BigInt& other) const {
        if (other.digits.size() == 1 && other.digits[0] == 0) {
            throw std::runtime_error("Division by zero");
        }
        BigInt quotient, remainder;
        absDivide(*this, other, quotient, remainder);
        quotient.isNegative = (isNegative != other.isNegative);
        if (quotient.digits.size() == 1 && quotient.digits[0] == 0) {
            quotient.isNegative = false;
        }
        return quotient;
    }

    // 取模
    BigInt operator%(const BigInt& other) const {
        if (other.digits.size() == 1 && other.digits[0] == 0) {
            throw std::runtime_error("Modulo by zero");
        }
        BigInt quotient, remainder;
        absDivide(*this, other, quotient, remainder);
        remainder.isNegative = isNegative;
        if (remainder.digits.size() == 1 && remainder.digits[0] == 0) {
            remainder.isNegative = false;
        }
        return remainder;
    }
};

// 实例用法
int main() {
    BigInt a("12345678901234567890");
    BigInt b("9876543210");

    std::cout << "a = " << a << std::endl;
    std::cout << "b = " << b << std::endl;
    std::cout << "a + b = " << a + b << std::endl;
    std::cout << "a - b = " << a - b << std::endl;
    std::cout << "a * b = " << a * b << std::endl;
    std::cout << "a / b = " << a / b << std::endl;
    std::cout << "a % b = " << a % b << std::endl;
    BigInt c("-12345");
    BigInt d("6789");
    std::cout << "c = " << c << ", d = " << d << std::endl;
    std::cout << "c + d = " << c + d << std::endl;
    std::cout << "c - d = " << c - d << std::endl;
    std::cout << "c * d = " << c * d << std::endl;
    std::cout << "c / d = " << c / d << std::endl;
    std::cout << "c % d = " << c % d << std::endl;

    return 0;
}
线段树SegmentTree
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
class SegmentTree {
private:
	int n;
	vector<ll> sum;
	vector<ll> lazy;
	void build(int node, int l, int r, const vector<ll>& arr) {
		if (l == r) {
			sum[node] = arr[l];
			return;
		}
		int mid = (l + r) / 2;
		build(node * 2, l, mid, arr);
		build(node * 2 + 1, mid + 1, r, arr);
		push_up(node);
	}
	void push_up(int node) {
		sum[node] = sum[node * 2] + sum[node * 2 + 1];
	}
	void push_down(int node, int l, int r) {
		if (lazy[node] != 0) {
			int mid = (l + r) / 2;
			lazy[node * 2] += lazy[node];
			sum[node * 2] += lazy[node] * (mid - l + 1);
			lazy[node * 2 + 1] += lazy[node];
			sum[node * 2 + 1] += lazy[node] * (r - mid);
			lazy[node] = 0;
		}
	}
	void update(int node, int l, int r, int ql, int qr, ll val) {
		if (ql <= l && r <= qr) {
			sum[node] += val * (r - l + 1);
			lazy[node] += val;
			return;
		}
		push_down(node, l, r);
		int mid = (l + r) / 2;
		if (ql <= mid) update(node * 2, l, mid, ql, qr, val);
		if (qr > mid) update(node * 2 + 1, mid + 1, r, ql, qr, val);
		push_up(node);
	}
	ll query(int node, int l, int r, int ql, int qr) {
		if (ql <= l && r <= qr) {
			return sum[node];
		}
		push_down(node, l, r);
		int mid = (l + r) / 2;
		ll res = 0;
		if (ql <= mid) res += query(node * 2, l, mid, ql, qr);
		if (qr > mid) res += query(node * 2 + 1, mid + 1, r, ql, qr);
		return res;
	}
public:
	SegmentTree(const vector<ll>& arr) {
		n = arr.size() - 1;
		sum.resize(4 * n);
		lazy.resize(4 * n, 0);
		build(1, 1, n, arr);
	}
	void range_add(int l, int r, ll val) {
		update(1, 1, n, l, r, val);
	}
	ll range_sum(int l, int r) {
		return query(1, 1, n, l, r);
	}
};
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n, m;
	cin >> n >> m;
	vector<ll> arr(n + 1);
	for (int i = 1; i <= n; ++i) {
		cin >> arr[i];
	}
	SegmentTree seg(arr);
	while (m--) {
		int op, x, y;
		ll k;
		cin >> op;
		if (op == 1) {
			cin >> x >> y >> k;
			seg.range_add(x, y, k);
		} else {
			cin >> x >> y;
			cout << seg.range_sum(x, y) << '\n';
		}
	}
	return 0;
}
AC自动机AhoCorasick
C++
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;

class AhoCorasick {
private:
    struct Node {
        int next[26];
        int fail;
        int cnt;               // 经过该节点的次数
        vector<int> out;        // 以该节点结尾的模式串编号列表
        Node() {
            fill(next, next + 26, 0);
            fail = 0;
            cnt = 0;
        }
    };

    vector<Node> trie;
    vector<int> order;          // BFS顺序(用于拓扑累加)

public:
    AhoCorasick() {
        trie.emplace_back();    // 根节点
    }

    // 插入模式串,idx为模式串编号(0-based)
    void insert(const string& s, int idx) {
        int u = 0;
        for (char ch : s) {
            int c = ch - 'a';
            if (trie[u].next[c] == 0) {
                trie[u].next[c] = trie.size();
                trie.emplace_back();
            }
            u = trie[u].next[c];
        }
        trie[u].out.push_back(idx);
    }

    // 构建fail指针,同时补全转移边(构建trie图)
    void build() {
        queue<int> q;
        // 初始化根节点的所有子节点
        for (int c = 0; c < 26; ++c) {
            if (trie[0].next[c]) {
                int v = trie[0].next[c];
                trie[v].fail = 0;
                q.push(v);
            } else {
                trie[0].next[c] = 0;   // 根节点缺失的边指向自己
            }
        }

        while (!q.empty()) {
            int u = q.front(); q.pop();
            order.push_back(u);
            for (int c = 0; c < 26; ++c) {
                int v = trie[u].next[c];
                if (v) {
                    trie[v].fail = trie[trie[u].fail].next[c];
                    q.push(v);
                } else {
                    trie[u].next[c] = trie[trie[u].fail].next[c];
                }
            }
        }
    }

    // 在文本串上匹配,统计每个节点被经过的次数
    void query(const string& s) {
        int u = 0;
        for (char ch : s) {
            int c = ch - 'a';
            u = trie[u].next[c];
            ++trie[u].cnt;
        }
    }

    // 将每个节点的cnt沿着fail指针累加到其fail节点(拓扑序逆序)
    void accumulate() {
        for (int i = order.size() - 1; i >= 0; --i) {
            int u = order[i];
            int f = trie[u].fail;
            trie[f].cnt += trie[u].cnt;
        }
    }

    // 获取每个模式串的出现次数
    vector<int> getResult(int totalPatterns) {
        vector<int> res(totalPatterns, 0);
        for (size_t i = 0; i < trie.size(); ++i) {
            for (int idx : trie[i].out) {
                res[idx] = trie[i].cnt;
            }
        }
        return res;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    vector<string> patterns(n);
    AhoCorasick ac;

    for (int i = 0; i < n; ++i) {
        cin >> patterns[i];
        ac.insert(patterns[i], i);
    }

    string text;
    cin >> text;

    ac.build();
    ac.query(text);
    ac.accumulate();

    vector<int> ans = ac.getResult(n);
    for (int x : ans) {
        cout << x << '\n';
    }

    return 0;
}
矩阵类Matrix
C++
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iomanip>

using namespace std;

class Matrix {
private:
	int n;
	vector<vector<double>> data;

public:
	Matrix(int size) : n(size), data(size, vector<double>(size, 0)) {}

	// 输入矩阵
	void input() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				cin >> data[i][j];
			}
		}
	}

	// 1. 判断是否是对角矩阵
	bool isDiagonal() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (i != j && abs(data[i][j]) > 1e-9) {
					return false;
				}
			}
		}
		return true;
	}

	// 2. 判断是否是0矩阵
	bool isZero() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (abs(data[i][j]) > 1e-9) {
					return false;
				}
			}
		}
		return true;
	}

	// 3. 判断是否是单位矩阵
	bool isIdentity() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (i == j) {
					if (abs(data[i][j] - 1.0) > 1e-9) {
						return false;
					}
				} else {
					if (abs(data[i][j]) > 1e-9) {
						return false;
					}
				}
			}
		}
		return true;
	}

	// 4. 判断是否是对称矩阵
	bool isSymmetric() {
		for (int i = 0; i < n; i++) {
			for (int j = i + 1; j < n; j++) {
				if (abs(data[i][j] - data[j][i]) > 1e-9) {
					return false;
				}
			}
		}
		return true;
	}

	// 5. 计算行列式(使用LU分解)
	double determinant() {
		vector<vector<double>> LU = data;
		vector<int> pivot(n);

		// LU分解
		for (int i = 0; i < n; i++) {
			pivot[i] = i;
		}

		double det = 1.0;

		for (int k = 0; k < n; k++) {
			// 部分选主元
			int max_row = k;
			for (int i = k + 1; i < n; i++) {
				if (abs(LU[i][k]) > abs(LU[max_row][k])) {
					max_row = i;
				}
			}

			if (max_row != k) {
				swap(LU[k], LU[max_row]);
				swap(pivot[k], pivot[max_row]);
				det = -det;
			}

			if (abs(LU[k][k]) < 1e-12) {
				return 0.0;
			}

			det *= LU[k][k];

			for (int i = k + 1; i < n; i++) {
				LU[i][k] /= LU[k][k];
				for (int j = k + 1; j < n; j++) {
					LU[i][j] -= LU[i][k] * LU[k][j];
				}
			}
		}

		return det;
	}

	// 6. 计算秩(使用高斯消元)
	int rank() {
		vector<vector<double>> mat = data;
		int rank = 0;

		for (int col = 0, row = 0; col < n && row < n; col++) {
			// 找到主元
			int pivot_row = row;
			for (int i = row + 1; i < n; i++) {
				if (abs(mat[i][col]) > abs(mat[pivot_row][col])) {
					pivot_row = i;
				}
			}

			if (abs(mat[pivot_row][col]) < 1e-12) {
				continue;
			}

			// 交换行
			if (pivot_row != row) {
				swap(mat[row], mat[pivot_row]);
			}

			// 消元
			for (int i = row + 1; i < n; i++) {
				double factor = mat[i][col] / mat[row][col];
				for (int j = col; j < n; j++) {
					mat[i][j] -= factor * mat[row][j];
				}
			}

			rank++;
			row++;
		}

		return rank;
	}

	// 7. 计算迹
	double trace() {
		double tr = 0.0;
		for (int i = 0; i < n; i++) {
			tr += data[i][i];
		}
		return tr;
	}

	// 8. 获取转置矩阵
	Matrix transpose() {
		Matrix result(n);
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				result.data[i][j] = data[j][i];
			}
		}
		return result;
	}

	// 9. 获取伴随矩阵
	Matrix adjugate() {
		double det = determinant();
		if (abs(det) < 1e-12) {
			return Matrix(n); // 返回0矩阵
		}

		// 伴随矩阵 = 逆矩阵 * 行列式
		Matrix inv_mat = inverse();
		Matrix adj(n);

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				adj.data[i][j] = inv_mat.data[i][j] * det;
			}
		}

		return adj;
	}

	// 10. 获取逆矩阵(使用LU分解)
	Matrix inverse() {
		double det = determinant();
		if (abs(det) < 1e-12) {
			throw "MAXIRT H IS ZERO";
		}

		// LU分解求逆矩阵
		vector<vector<double>> LU = data;
		vector<int> pivot(n);

		// 初始化置换矩阵
		for (int i = 0; i < n; i++) {
			pivot[i] = i;
		}

		// LU分解
		for (int k = 0; k < n; k++) {
			// 部分选主元
			int max_row = k;
			for (int i = k + 1; i < n; i++) {
				if (abs(LU[i][k]) > abs(LU[max_row][k])) {
					max_row = i;
				}
			}

			if (max_row != k) {
				swap(LU[k], LU[max_row]);
				swap(pivot[k], pivot[max_row]);
			}

			for (int i = k + 1; i < n; i++) {
				LU[i][k] /= LU[k][k];
				for (int j = k + 1; j < n; j++) {
					LU[i][j] -= LU[i][k] * LU[k][j];
				}
			}
		}

		// 解方程 LY = I 和 UX = Y
		Matrix inv(n);

		for (int col = 0; col < n; col++) {
			// 前向代入解 LY = I
			vector<double> y(n, 0);
			for (int i = 0; i < n; i++) {
				y[i] = (pivot[i] == col) ? 1.0 : 0.0;
				for (int j = 0; j < i; j++) {
					y[i] -= LU[i][j] * y[j];
				}
			}

			// 后向代入解 UX = Y
			for (int i = n - 1; i >= 0; i--) {
				inv.data[i][col] = y[i];
				for (int j = i + 1; j < n; j++) {
					inv.data[i][col] -= LU[i][j] * inv.data[j][col];
				}
				inv.data[i][col] /= LU[i][i];
			}
		}

		return inv;
	}

	// 输出矩阵
	void print() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (abs(data[i][j]) < 1e-9) {
					cout << "0";
				} else if (abs(data[i][j] - round(data[i][j])) < 1e-9) {
					cout << static_cast<int>(round(data[i][j]));
				} else {
					cout << fixed << setprecision(6) << data[i][j];
				}
				if (j < n - 1) cout << " ";
			}
			cout << endl;
		}
	}
};

int main() {
	int n;
	cin >> n;

	Matrix mat(n);
	mat.input();

	// 1. 对角矩阵判断
	cout << (mat.isDiagonal() ? 1 : 0) << endl;

	// 2. 0矩阵判断
	cout << (mat.isZero() ? 1 : 0) << endl;

	// 3. 单位矩阵判断
	cout << (mat.isIdentity() ? 1 : 0) << endl;

	// 4. 对称矩阵判断
	cout << (mat.isSymmetric() ? 1 : 0) << endl;

	// 5. 行列式
	double det = mat.determinant();
	if (abs(det) < 1e-9) {
		cout << "0" << endl;
	} else if (abs(det - round(det)) < 1e-9) {
		cout << static_cast<int>(round(det)) << endl;
	} else {
		cout << fixed << setprecision(6) << det << endl;
	}

	// 6. 秩
	cout << mat.rank() << endl;

	// 7. 迹
	double tr = mat.trace();
	if (abs(tr - round(tr)) < 1e-9) {
		cout << static_cast<int>(round(tr)) << endl;
	} else {
		cout << fixed << setprecision(6) << tr << endl;
	}

	// 8. 转置矩阵
	mat.transpose().print();

	// 9. 伴随矩阵
	mat.adjugate().print();

	// 10. 逆矩阵
	try {
		mat.inverse().print();
	} catch (const char* msg) {
		cout << msg << endl;
	}

	return 0;
}
重剖部分HeavyLightDecomposition
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;

class HeavyLightDecomposition {
private:
	int N, R, MOD;
	vector<vector<int>> g;
	vector<int> fa, dep, siz, son, top, id, rnk;
	int cnt;

	// 内部线段树类
	class SegmentTree {
	private:
		int n;
		int mod;
		vector<ll> sum, lazy;

		void push_up(int rt) {
			sum[rt] = (sum[rt << 1] + sum[rt << 1 | 1]) % mod;
		}

		void push_down(int rt, int l, int r) {
			if (lazy[rt] != 0) {
				int mid = (l + r) >> 1;
				lazy[rt << 1] = (lazy[rt << 1] + lazy[rt]) % mod;
				lazy[rt << 1 | 1] = (lazy[rt << 1 | 1] + lazy[rt]) % mod;
				sum[rt << 1] = (sum[rt << 1] + lazy[rt] * (mid - l + 1)) % mod;
				sum[rt << 1 | 1] = (sum[rt << 1 | 1] + lazy[rt] * (r - mid)) % mod;
				lazy[rt] = 0;
			}
		}

		void build(int rt, int l, int r, const vector<int>& arr) {
			if (l == r) {
				sum[rt] = arr[l] % mod;
				return;
			}
			int mid = (l + r) >> 1;
			build(rt << 1, l, mid, arr);
			build(rt << 1 | 1, mid + 1, r, arr);
			push_up(rt);
		}

		void update(int rt, int l, int r, int ql, int qr, int val) {
			if (ql <= l && r <= qr) {
				sum[rt] = (sum[rt] + (ll)val * (r - l + 1)) % mod;
				lazy[rt] = (lazy[rt] + val) % mod;
				return;
			}
			push_down(rt, l, r);
			int mid = (l + r) >> 1;
			if (ql <= mid) update(rt << 1, l, mid, ql, qr, val);
			if (qr > mid) update(rt << 1 | 1, mid + 1, r, ql, qr, val);
			push_up(rt);
		}

		ll query(int rt, int l, int r, int ql, int qr) {
			if (ql <= l && r <= qr) return sum[rt];
			push_down(rt, l, r);
			int mid = (l + r) >> 1;
			ll res = 0;
			if (ql <= mid) res = (res + query(rt << 1, l, mid, ql, qr)) % mod;
			if (qr > mid) res = (res + query(rt << 1 | 1, mid + 1, r, ql, qr)) % mod;
			return res;
		}

	public:
		SegmentTree(int _n, int _mod) : n(_n), mod(_mod) {
			sum.resize(4 * n);
			lazy.resize(4 * n, 0);
		}

		void build(const vector<int>& arr) {
			build(1, 1, n, arr);
		}

		void range_add(int l, int r, int val) {
			if (l > r) return;
			update(1, 1, n, l, r, val);
		}

		ll range_sum(int l, int r) {
			if (l > r) return 0;
			return query(1, 1, n, l, r);
		}
	};

	SegmentTree seg;

	void dfs1(int u, int f) {
		fa[u] = f;
		dep[u] = dep[f] + 1;
		siz[u] = 1;
		son[u] = 0;
		for (int v : g[u]) {
			if (v == f) continue;
			dfs1(v, u);
			siz[u] += siz[v];
			if (siz[v] > siz[son[u]]) son[u] = v;
		}
	}

	void dfs2(int u, int t) {
		top[u] = t;
		id[u] = ++cnt;
		rnk[cnt] = u;
		if (son[u]) dfs2(son[u], t);
		for (int v : g[u]) {
			if (v == fa[u] || v == son[u]) continue;
			dfs2(v, v);
		}
	}

public:
	HeavyLightDecomposition(int n, int root, int mod, const vector<vector<int>>& graph, const vector<int>& init)
	: N(n), R(root), MOD(mod), g(graph), cnt(0), seg(n, mod) {
		fa.resize(N + 1);
		dep.resize(N + 1);
		siz.resize(N + 1);
		son.resize(N + 1);
		top.resize(N + 1);
		id.resize(N + 1);
		rnk.resize(N + 1);
		dfs1(R, 0);
		dfs2(R, R);
		// 构建按 dfs 序排列的数组
		vector<int> dfs_order(N + 1);
		for (int i = 1; i <= N; ++i) {
			dfs_order[id[i]] = init[i] % MOD;
		}
		seg.build(dfs_order);
	}

	// 路径加
	void path_add(int x, int y, int z) {
		z %= MOD;
		while (top[x] != top[y]) {
			if (dep[top[x]] < dep[top[y]]) swap(x, y);
			seg.range_add(id[top[x]], id[x], z);
			x = fa[top[x]];
		}
		if (dep[x] > dep[y]) swap(x, y);
		seg.range_add(id[x], id[y], z);
	}

	// 路径求和
	ll path_sum(int x, int y) {
		ll res = 0;
		while (top[x] != top[y]) {
			if (dep[top[x]] < dep[top[y]]) swap(x, y);
			res = (res + seg.range_sum(id[top[x]], id[x])) % MOD;
			x = fa[top[x]];
		}
		if (dep[x] > dep[y]) swap(x, y);
		res = (res + seg.range_sum(id[x], id[y])) % MOD;
		return res;
	}

	// 子树加
	void subtree_add(int x, int z) {
		z %= MOD;
		seg.range_add(id[x], id[x] + siz[x] - 1, z);
	}

	// 子树求和
	ll subtree_sum(int x) {
		return seg.range_sum(id[x], id[x] + siz[x] - 1);
	}
};

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	int N, M, R, P;
	cin >> N >> M >> R >> P;
	vector<int> init(N + 1);
	for (int i = 1; i <= N; ++i) {
		cin >> init[i];
	}
	vector<vector<int>> g(N + 1);
	for (int i = 1; i < N; ++i) {
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}

	HeavyLightDecomposition hld(N, R, P, g, init);

	while (M--) {
		int op, x, y, z;
		cin >> op;
		if (op == 1) {
			cin >> x >> y >> z;
			hld.path_add(x, y, z);
		} else if (op == 2) {
			cin >> x >> y;
			cout << hld.path_sum(x, y) << '\n';
		} else if (op == 3) {
			cin >> x >> z;
			hld.subtree_add(x, z);
		} else { // op == 4
			cin >> x;
			cout << hld.subtree_sum(x) << '\n';
		}
	}
	return 0;
}
集合类Set
C++
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <utility>

template<typename T>
class Set {
private:
	std::set<T> elements;

public:
	// 构造函数
	Set() {}
	Set(const std::initializer_list<T>& list) : elements(list) {}

	// 基本操作
	void insert(const T& value) { elements.insert(value); }
	void erase(const T& value) { elements.erase(value); }
	bool contains(const T& value) const { return elements.find(value) != elements.end(); }
	size_t size() const { return elements.size(); }

	// 迭代器
	auto begin() const { return elements.begin(); }
	auto end() const { return elements.end(); }

	// 并集
	Set<T> Union(const Set<T>& other) const {
		Set<T> result;
		std::set_union(elements.begin(), elements.end(),
			other.elements.begin(), other.elements.end(),
			std::inserter(result.elements, result.elements.begin()));
		return result;
	}

	// 交集
	Set<T> Intersection(const Set<T>& other) const {
		Set<T> result;
		std::set_intersection(elements.begin(), elements.end(),
			other.elements.begin(), other.elements.end(),
			std::inserter(result.elements, result.elements.begin()));
		return result;
	}

	// 差集(当前集合减去 other)
	Set<T> Difference(const Set<T>& other) const {
		Set<T> result;
		std::set_difference(elements.begin(), elements.end(),
			other.elements.begin(), other.elements.end(),
			std::inserter(result.elements, result.elements.begin()));
		return result;
	}

	// 补集:返回全集(参数)减去当前集合
	Set<T> Complement(const Set<T>& universe) const {
		return universe.Difference(*this);
	}

	// 笛卡尔积:返回 Set<pair<T,T>>
	Set<std::pair<T,T>> CartesianProduct(const Set<T>& other) const {
		Set<std::pair<T,T>> result;
		for (const T& a : elements) {
			for (const T& b : other.elements) {
				result.insert(std::make_pair(a, b));
			}
		}
		return result;
	}

	// 输出运算符重载
	friend std::ostream& operator<<(std::ostream& os, const Set<T>& set) {
		os << "{";
		bool first = true;
		for (const T& elem : set.elements) {
			if (!first) os << ", ";
			os << elem;
			first = false;
		}
		os << "}";
		return os;
	}
};

// 为 std::pair 提供输出支持
template<typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& p) {
	os << "(" << p.first << "," << p.second << ")";
	return os;
}

// 示例用法
int main() {
	Set<int> set1 = {1, 2, 3, 4, 5};
	Set<int> set2 = {4, 5, 6, 7};

	std::cout << "set1 = " << set1 << std::endl;
	std::cout << "set2 = " << set2 << std::endl;

	std::cout << "Union: " << set1.Union(set2) << std::endl;
	std::cout << "Intersection: " << set1.Intersection(set2) << std::endl;
	std::cout << "Difference (set1 - set2): " << set1.Difference(set2) << std::endl;
	// 补集:以 set1 为全集,求 set2 的补 → set1 - set2
	std::cout << "Complement of set2 w.r.t set1: " << set2.Complement(set1) << std::endl;

	auto cp = set1.CartesianProduct(set2);
	std::cout << "Cartesian Product: " << cp << std::endl;

	return 0;
}
原文