跳到正文

题解

题解:P15943 [JOI Final 2026] JOI 之旅 2 / JOI Tour 2

EricWan约 49 分钟
原文
文章信息与版本

文章信息

收录
2026年6月12日
更新
2026年6月14日
篇幅
约 49 分钟
获赞
2
题目
P15943

版本

  1. v3当前
  2. v2
  3. v1

转置原理太牛了,作为一个麻瓜我终于大致懂了这个玄学。

我也不知道要咋讲这个魔法,就按照 Caii 老师讲的顺序讲吧。但是我省略了转置算法这些部分,因为这些是理解这个题不需要的。

但是为了符合我之前使用矩阵的习惯,我会把新乘的系数写在后面,大部分向量采用横向向量,这样应该也对理解最后求答案的时候为啥要倒着乘转移矩阵的转置要有帮助。

转置原理理论部分不在乎下标开始位置。


转置原理

首先下面两个问题可以互相转化:

  1. 【给定巴拉巴拉,包括这个题的树的结构等其他输入,包括那个 BB】,求 x1,…,xqx_1,\dots,x_q。也就是这题要问的答案。
  2. 【同样给定上面的所有东西】,再给定 w1,…,wqw_1,\dots,w_q,问 ∑i=1qxiwi\sum\limits_{i=1}^qx_iw_i。

接下来就要使用魔法说明为什么了。

定义一个算法为接收一个矩阵返回一个矩阵的东西。叫做函数是不是更好。定义线性算法为 A(αX+βY)=αA(X)+βA(Y)\mathcal{A}(\alpha\mathbf{X}+\beta\mathbf{Y})=\alpha\mathcal{A}(\mathbf{X})+\beta\mathcal{A}(\mathbf{Y}) 的算法,那么可以证明 A\mathcal{A} 等价于把输入乘以一个矩阵,称其为 A\mathbf{A},为了符合我的习惯,我会把 A(X)\mathcal{A}(\mathbf{X}) 写成 XA\mathbf{XA}。我也不会证,这个定理是玄学,我是麻瓜。这个真的是做这个题必须用的性质吗,我不知道。

任何方阵都可以写作若干基本矩阵的乘积,每一个基本矩阵都形如单位矩阵的某一格增加一个数。我们称 n×nn\times n 单位矩阵在第 ii 行第 jj 列增加 kk 的基本矩阵记作 Pn(i,j,k)\mathbf{P}_n(i,j,k)(也许和更加标准的写法不同,但是这些已经够用了)。一个横向向量乘上这个矩阵就等价与第 jj 个数加上第 ii 个数的 kk 倍。

一个向量乘一个基本矩阵都可以映射到某一位增加某一位的若干倍这个操作。因此我们知道这个算法的一个运算过程,这个过程中只包括 a += k * b 这样的运算就可以还原出这个算法的等价矩阵,但是暴力乘两个矩阵是三次方的,还需要做非常多步,显然太慢,后面会讲神奇的东西。

考虑构造一个线性算法 A([w1…wq])=[w1…wq][x1⋮xq]\mathcal{A}(\begin{bmatrix}w_1&&\dots&&w_q\end{bmatrix})=\begin{bmatrix}w_1&&\dots&&w_q\end{bmatrix}\begin{bmatrix}x_1\\\vdots\\x_q\end{bmatrix} 返回值大小为 1×11\times1,这就是上文的第二个问题。如果可以只通过若干变量包括 ww,只使用 a += k * b 这样的操作得到答案,则我们声称可以迅速还原出 xx。(注意这里认为树的结构、输入的 AA、输入的 BB、那些路径等等都是已知量,怎样循环怎样 a += k * b 什么的是外围的事情,理解这一点很重要。也就是说,只有全部有关 ww 的计算必须写成线性的乘基本矩阵,只有 ww 是第二个题的算法的输入。)

如果我们还需要 tmptmp 个临时变量(还也许可能需要一个常量全程为 11 方便数加,不过这题不需要),则我们解决上文的第二个问题的算法可以写为这样的形式:

[w1…wq0…0]Pq+tmp(i1,j1,k1)Pq+tmp(i2,j2,k2)…Pq+tmp(io,jo,ko)[0⋮010⋮0]\begin{bmatrix}w_1&&\dots&&w_q&&0&&\dots&&0\end{bmatrix}\mathbf{P}_{q+tmp}(i_1,j_1,k_1)\mathbf{P}_{q+tmp}(i_2,j_2,k_2)\dots\mathbf{P}_{q+tmp}(i_o,j_o,k_o)\begin{bmatrix}0\\\vdots\\0\\1\\0\\\vdots\\0\end{bmatrix}

第一个矩阵为未知的 ww 和若干需要使用的临时变量,最后一个矩阵用来提取出用于存储答案的变量作为返回。那么我们发现做第二个题目的算法的后面 Pq+tmp(i1,j1,k1)Pq+tmp(i2,j2,k2)…Pq+tmp(io,jo,ko)[0⋮010⋮0]\mathbf{P}_{q+tmp}(i_1,j_1,k_1)\mathbf{P}_{q+tmp}(i_2,j_2,k_2)\dots\mathbf{P}_{q+tmp}(i_o,j_o,k_o)\begin{bmatrix}0\\\vdots\\0\\1\\0\\\vdots\\0\end{bmatrix} 这一坨就恰好乘起来前 qq 位为需要的 xx。

称 n=q+tmpn=q+tmp。想要把这些矩阵乘起来,考虑从后往前做,可以发现:

Pn(i,j,k)[x1⋮xn]=([x1…xn]Pn(j,i,k))⊤=[x1⋮xi−1xi+k×xjxi+1⋮xn]\mathbf{P}_n(i,j,k)\begin{bmatrix}x_1\\\vdots\\x_n\end{bmatrix}=(\begin{bmatrix}x_1&&\dots&&x_n\end{bmatrix}\mathbf{P}_n(j,i,k))^\top=\begin{bmatrix}x_1\\\vdots\\x_{i-1}\\x_i+k\times x_j\\x_{i+1}\\\vdots\\x_n\end{bmatrix}

这样就可以 O(1)O(1) 乘上一个基本矩阵了,逆着做整个算法可以 O(o)O(o) 还原出需要的 xx,而我们只需设计解决第二问的算法,把整个算法计算过程反过来即可。

这样我们论证了我们只要能解决下面的问题就能把计算过程倒过来还原 xx。


链

考虑莫队,我们把 MM 个路径当做查询来做,对于每移动一个边界,我们需要找这个新的元素(或被删除的元素)和线段内部的元素的和的贡献,如果是某个查询就是一次某一个 ww 的贡献,否则没有贡献。我们可以维护一个数组记录每一种新加入的数值会做出的贡献,一个在区间中的数 AiA_i 会对每一个 Bj≥AiB_j\ge A_i 做出 wjw_j 的贡献在 Bj−AiB_j-A_i。但是这样区间每移动一次就需要 O(q)O(q) 的复杂度来更新这个数组,总共需要移动 O(MN)O(M\sqrt N) 次,所以复杂度爆了,之后上莫队二离板子就行。

洛谷的莫队二离板子非常清新,没做过先去写一下 https://www.luogu.com.cn/problem/P4887。


树

从深向浅按高度分块,之后就是树上莫队了。

复杂度 O((M+N)N+NQ)O((M+N)\sqrt N+NQ),空间复杂度精细实现可以线性。一亿倍大常数。

这样就做完了。


代码

妈的,谁爱写谁写去吧。


不会狂暴维护路径的树上莫队咋办

再次考虑链,把 l≤u<v≤rl\le u<v\le r 容斥出来。如果我们可以求出 1≤u=v≤i1\le u=v\le i 这样的 (u,v)(u,v) 数量,和 1≤u≤i1\le u\le i 且 1≤v≤j1\le v\le j 的 (u,v)(u,v) 数量。(好像这里就和别的生成函数题解的做法贴近了。)可以把 l≤u<v≤rl\le u<v\le r 拆成上面的两种东西加加建减,而上面的第一个东西是好求的,第二个东西仍然可以莫队。

把这个思想搬到树上,把上面类似 1≤u≤i1\le u\le i 这样的限制改为 uu 为 ii 的祖先,跑莫队就好写得多。定义 f(i,j)f(i,j) 为 uu 为 ii 的祖先且 vv 为 jj 的祖先的 Au+AvA_u+A_v 产生的价值之和。定义 g(i)g(i) 为 uu 为 ii 的祖先的时候 2Au2A_u 产生的价值的和,定义 faifa_i 为 ii 的爹,关于根的爹的 ff 均为 00。则路径 x→yx\rightarrow y 的答案可以凑出容斥系数:

太绕了分开写:

分为 x↔LCA⁡(x,y)x\leftrightarrow\operatorname{LCA}(x,y) 这一段和剩下的部分。ff 的结构很具备分配率,因此一个段和一个段的产生的价值可以用分配律拆成 ff。

前一部分的内部贡献 f(x,x)−2f(x,faLCA⁡(x,y))+f(faLCA⁡(x,y),faLCA⁡(x,y))−g(x)+g(faLCA⁡(x,y))2\frac{f(x,x)-2f(x,fa_{\operatorname{LCA}(x,y)})+f(fa_{\operatorname{LCA}(x,y)},fa_{\operatorname{LCA}(x,y)})-g(x)+g(fa_{\operatorname{LCA}(x,y)})}2;
第二部分贡献 f(y,y)−2f(y,LCA⁡(x,y))+f(LCA⁡(x,y),LCA⁡(x,y))−g(y)+g(LCA⁡(x,y))2\frac{f(y,y)-2f(y,\operatorname{LCA}(x,y))+f(\operatorname{LCA}(x,y),\operatorname{LCA}(x,y))-g(y)+g(\operatorname{LCA}(x,y))}2;
第一部分选 uu,第二部分选 vv 贡献 f(x,y)−f(faLCA⁡(x,y),y)−f(x,LCA⁡(x,y))+f(faLCA⁡(x,y),LCA⁡(x,y))f(x,y)-f(fa_{\operatorname{LCA}(x,y)},y)-f(x,\operatorname{LCA}(x,y))+f(fa_{\operatorname{LCA}(x,y)},\operatorname{LCA}(x,y))。

求这个 ff 需要把树按 DFS 序拍平,每个点拆成进入和走出,走出产生负一倍贡献,这样就跑到序列上了

怎么莫队是外围的事,考虑正着做有关 ww 的计算会有哪几步,首先会在树的 DFS 序上处理二次离线的需求(包括在桶里某些位置增加 ww,根据桶增加),之后做前缀和求出需要的 ff,之后把十个 ff 加起来求出一个原路径的价值,之后求所有原路径的价值和。

倒观上面这一段,是真正的按字倒背,再翻译为简体中文,得到下面的东西:把所有路径的价值设为 11,把需要的十个 ff 的价值标记上,把排序后的 ff 的价值做后缀和,二次离线,DFS 序上处理这些需求(包括把需求加入桶,根据 B−AB-A 的桶标记对应的 ww 的价值)。ww 的价值也就是 xx。

有关 gg 的部分,正着做是这样的,根据 2Au2A_u 决定是否是 00 或某一个 ww,做树上前缀和得到 gg,求出对每个原路径的贡献,求和。

倒着看就是每个原路径的价值是 11,求出每个 gg 的价值,求出 gg 的价值的子树和,就是单点价值,根据 AA 确定是否需要用这个价值更新一个 xx。

然后就做完了?


1010 倍大常数代码

代码
C++
#include <bits/stdc++.h>
// #include <bits/extc++.h>
#define multiple_cases(T) signed T; cin >> T; while (T--)
#define variable_name(x) #x
#define all(x) (x).begin(), (x).end()
#define adebug(a, b, c) #a << "[" << (b) << "..." << (c) << "] = " << vector<typename decay<decltype(*((a) + (b)))>::type>((a) + (b), (a) + (c) + 1)
#define file_io(a) (freopen(#a ".in", "r", stdin), freopen(#a ".out", "w", stdout))
#ifdef assert
#undef assert
#endif
#define assert(x) if (!(x)) { std::cerr << "Assertion failed: " << #x << ", line " << __LINE__ << std::endl; exit(1); } else;
using namespace std;
// using namespace __gnu_cxx;
// using namespace __gnu_pbds;
namespace quick_io {
	template<typename... Args>
	ostream& operator<<(ostream& os, const tuple<Args...>& t);
	template<typename T, typename Alloc>
	ostream &operator<<(ostream &A, const vector<T, Alloc> &b);
	template<typename T, typename Alloc>
	ostream &operator<<(ostream &A, const deque<T, Alloc> &b);
	template<typename T1, typename T2>
	ostream &operator<<(ostream &A, const pair<T1, T2> &b);
	template<typename T, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const set<T, Compare, Alloc> &b);
	template<typename T, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const multiset<T, Compare, Alloc> &b);
	template<typename T, typename T2, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const map<T, T2, Compare, Alloc> &b);
	template<typename T, typename T2, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const multimap<T, T2, Compare, Alloc> &b);
	template<typename T, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_set<T, Hash, KeyEqual, Alloc> &b);
	template<typename T, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_multiset<T, Hash, KeyEqual, Alloc> &b);
	template<typename T, typename T2, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_map<T, T2, Hash, KeyEqual, Alloc> &b);
	template<typename T, typename T2, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_multimap<T, T2, Hash, KeyEqual, Alloc> &b);
	template<typename T, typename Alloc>
	ostream &operator<<(ostream &A, const vector<T, Alloc> &b) {
		A << "[";
		for (typename vector<T, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "]";
	}
	template<typename T, typename Alloc>
	ostream &operator<<(ostream &A, const deque<T, Alloc> &b) {
		A << "[";
		for (typename deque<T, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "]";
	}
	template<typename T1, typename T2>
	ostream &operator<<(ostream &A, const pair<T1, T2> &b) {
		return A << '(' << b.first << ',' << b.second << ')';
	}
	template<typename T, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const set<T, Compare, Alloc> &b) {
		A << "{";
		for (typename set<T, Compare, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const multiset<T, Compare, Alloc> &b) {
		A << "{";
		for (typename multiset<T, Compare, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename T2, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const map<T, T2, Compare, Alloc> &b) {
		A << "{";
		for (typename map<T, T2, Compare, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename T2, typename Compare, typename Alloc>
	ostream &operator<<(ostream &A, const multimap<T, T2, Compare, Alloc> &b) {
		A << "{";
		for (typename multimap<T, T2, Compare, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_set<T, Hash, KeyEqual, Alloc> &b) {
		A << "{";
		for (typename unordered_set<T, Hash, KeyEqual, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_multiset<T, Hash, KeyEqual, Alloc> &b) {
		A << "{";
		for (typename unordered_multiset<T, Hash, KeyEqual, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename T2, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_map<T, T2, Hash, KeyEqual, Alloc> &b) {
		A << "{";
		for (typename unordered_map<T, T2, Hash, KeyEqual, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	template<typename T, typename T2, typename Hash, typename KeyEqual, typename Alloc>
	ostream &operator<<(ostream &A, const unordered_multimap<T, T2, Hash, KeyEqual, Alloc> &b) {
		A << "{";
		for (typename unordered_multimap<T, T2, Hash, KeyEqual, Alloc>::const_iterator it = b.begin(); it != b.end(); ++it) {
			if (it != b.begin()) A << ",";
			A << *it;
		}
		return A << "}";
	}
	void print_tuple(ostream&, const tuple<>&) {}
	template<typename T, typename... Rest>
	void print_tuple(ostream& os, const tuple<T, Rest...>& t) {
		os << get<0>(t);
	    if (sizeof...(Rest) > 0) {
			os << ",";
			print_tuple(os, reinterpret_cast<const tuple<Rest...>&>(t));
		}
	}
	template<typename... Args>
	ostream& operator<<(ostream& os, const tuple<Args...>& t) {
		os << "(";
	    print_tuple(os, t);
		return os << ")";
	}
	template<typename T1, typename T2>
	istream &operator>>(istream &A, pair<T1, T2> &b) {
		return A >> b.first >> b.second;
	}
	template<typename T>
	void print_array(T b, T e, string s = " ") {
		while (b != e) {
			cout << *b;
			b++;
			if (b != e) {
				cout << s;
			}
		}
	}
	template<typename T>
	void auto_print(T &b, size_t n, string s = " ") {
		for (size_t i = 1; i < n; i++) {
			cout << b[i] << s;
		}
		cout << b[n];
	}
	template<typename T>
	void auto_print(T &b, string s = " ") {
		for (auto i : b) {
			cout << i << s;
		}
	}
	template<typename T>
	void print_n(T b, size_t n, string s = " ") {
		if (n == 0) return;
		cout << *b;
		for (size_t i = 1; i < n; i++) {
			b++;
			cout << s << *b;
		}
	}
	template<typename T>
	void read_array(T b, T e) {
		while (b != e) {
			cin >> *b;
			b++;
		}
	}
	template<typename T>
	void auto_read(T &b, size_t n) {
		for (size_t i = 1; i <= n; i++) {
			cin >> b[i];
		}
	}
	template<typename T>
	void read_n(T b, size_t n) {
		cin >> *b;
		for (size_t i = 1; i < n; i++) {
			b++;
			cin >> *b;
		}
	}
	template <typename T>
	std::string to_string(const T& value) {
		std::ostringstream oss;
		oss << value;
		return oss.str();
	}
	std::string debug_index() {
		return "";
	}
	template <typename first_t, typename... rest_t>
	std::string debug_index(const first_t& first, const rest_t&... rest) {
		return "[" + to_string(first) + "]" + debug_index(rest...);
	}
	template <typename T>
	auto get_value(T&& arr) -> decltype(std::forward<T>(arr)) {
		return std::forward<T>(arr);
	}
	template <typename T, typename first_t, typename... rest_t>
	auto get_value(T&& arr, first_t&& first, rest_t&&... rest) {
		return get_value(
			std::forward<T>(arr)[std::forward<first_t>(first)],
			std::forward<rest_t>(rest)...
		);
	}
	#define debug(first, ...) #first << debug_index(__VA_ARGS__) << " = " << get_value(first, ##__VA_ARGS__)
	#define spc << ' ' <<
	#undef quick_io_int_length_limit
	#undef quick_io_int_radix_type
	#undef quick_io_length_type
}
using namespace quick_io;
namespace fast_ios {
	// #define fast_ios_buffer_enough
	// #define fast_is_buffer_enough
	// #define fast_os_buffer_enough
	// #define fast_ios_jump_invisible
	// #define fast_is_jump_invisible
	// #define fast_os_jump_invisible
	#ifdef fast_ios_buffer_enough
		#define fast_is_buffer_enough
		#define fast_os_buffer_enough
	#endif
	#ifdef fast_ios_jump_invisible
		#define fast_is_jump_invisible
		#define fast_os_jump_invisible
	#endif
	template<size_t buffer_size = 65536>
	struct fast_reader_t {
		// short, int, long, long long, __int128
		// unsigned short, int, long, long long, __int128
		// very safe if there are no overflow
		size_t cursor;
		unsigned char c;
		unsigned char buffer[buffer_size];
		inline fast_reader_t() : cursor(buffer_size), c(EOF) {}
		inline unsigned char &get() {
			#ifndef fast_is_buffer_enough
			if (cursor < buffer_size) {
			#endif
				return c = buffer[cursor++];
			#ifndef fast_is_buffer_enough
			}
			for (size_t i = fread(buffer, 1, buffer_size, stdin); i < buffer_size; i++) {
				buffer[i] = EOF;
			}
			return c = buffer[(cursor = 0)++];
			#endif
		}
		inline void unget() {
			cursor--;
		}
		template<typename T>
		typename enable_if<is_integral<T>::value
						&& is_unsigned<T>::value
						&& !is_same<T, unsigned char>::value
						 , fast_reader_t&>::type
		inline operator>>(T &x) {
			x = 0;
			while (get() < '0' || c > '9');
			do {
				x = (x << 3) + (x << 1) + (c ^ '0');
			} while (get() >= '0' && c <= '9');
			#ifndef fast_is_jump_invisible
			unget();
			#endif
			return *this;
		}
		template<typename T>
		typename enable_if<is_integral<T>::value
						&& is_signed<T>::value
						&& !is_same<T, char>::value
						 , fast_reader_t&>::type
		inline operator>>(T &x) {
			typename make_unsigned<T>::type x_ = 0;
			bool sign = false;
			while ((get() < '0' || c > '9') && c != '-' && c != '+');
			if (c == '-') {
				sign = true;
				get();
			} else if (c == '+') {
				get();
			}
			do {
				x_ = (x_ << 3) + (x_ << 1) + (c ^ '0');
			} while (get() >= '0' && c <= '9');
			x = x_;
			if (sign) {
				x = -x;
			}
			#ifndef fast_is_jump_invisible
			unget();
			#endif
			return *this;
		}
		inline fast_reader_t &operator>>(char &x) {
			while (!isgraph(get()));
			x = c;
			return *this;
		}
		inline fast_reader_t &operator>>(unsigned char &x) {
			while (!isgraph(get()));
			x = c;
			return *this;
		}
		inline fast_reader_t &operator>>(string &x) {
			x = "";
			while (get() <= 32);
			do {
				x += c;
			} while (get() > 32);
			#ifndef fast_is_jump_invisible
			unget();
			#endif
			return *this;
		}
		inline fast_reader_t &operator>>(char *x) {
			while (get() <= 32);
			do {
				*(x++) = c;
			} while (get() > 32);
			*x = 0;
			#ifndef fast_is_jump_invisible
			unget();
			#endif
			return *this;
		}
		template<typename T>
		typename enable_if<is_floating_point<T>::value, fast_reader_t&>::type
		inline operator>>(T &x) {
			x = 0;
			bool sign = false;
			while ((get() < '0' || c > '9') && c != '-' && c != '+' && c != '.');
			if (c == '-') {
				sign = true;
				get();
			} else if (c == '+') {
				get();
			} else if (c == '.') {
				unget();
			}
			if (c != '.') do {
				x = x * 10 + (c ^ '0');
			} while (get() >= '0' && c <= '9');
			if (c == '.') {
				T f = 0.1;
				while (get() >= '0' && c <= '9') {
					x += (c ^ '0') * f;
					f /= 10;
				}
			}
			if (sign) {
				x = -x;
			}
			unget();
			return *this;
		}
	};
	template<size_t buffer_size = 65536>
	struct fast_writer_t {
		// short, int, long, long long, __int128
		// unsigned short, int, long, long long, __int128
		size_t cursor;
		unsigned char buffer[buffer_size];
		inline fast_writer_t() : cursor(0) {}
		inline ~fast_writer_t() {
			if (cursor) {
				flush();
			}
		}
		inline void flush() {
			__builtin_fwrite(buffer, 1, cursor, stdout);
			cursor = 0;
		}
		inline void put(unsigned char c) {
			buffer[cursor++] = c;
			#ifndef fast_os_buffer_enough
			if (cursor == buffer_size) {
				flush();
			}
			#endif
		}
		template<typename T>
		typename enable_if<is_integral<T>::value
						&& is_unsigned<T>::value
						&& !is_same<unsigned char, T>::value,
						fast_writer_t&>::type
		inline operator<<(const T &x) {
			if (x >= T(10)) {
				*this << x / T(10);
			}
			put('0' ^ x % T(10));
			return *this;
		}
		template<typename T>
		typename enable_if<is_integral<T>::value
						&& is_signed<T>::value
						&& !is_same<char, T>::value,
						fast_writer_t&>::type
		inline operator<<(const T &x) {
			if (x >= T(0)) {
				return *this << (typename make_unsigned<T>::type)x;
			} else {
				put('-');
				return *this << (typename make_unsigned<T>::type)(-x);
			}
		}
		inline fast_writer_t &operator<<(char x) {
			put(x);
			return *this;
		}
		inline fast_writer_t &operator<<(unsigned char x) {
			put(x);
			return *this;
		}
		inline fast_writer_t &operator<<(const string &x) {
			for (string::const_iterator it = x.cbegin(); it != x.cend(); it++) {
				put(*it);
			}
			return *this;
		}
		inline fast_writer_t &operator<<(const char *x) {
			while (*x) {
				put(*(x++));
			}
			return *this;
		}
		inline fast_writer_t &operator<<(const unsigned char *x) {
			while (*x) {
				put(*(x++));
			}
			return *this;
		}
	};
	fast_reader_t<> ewin;
	fast_writer_t<> ewout;
}
template<typename T_key,
		 typename T_value,
		 typename head_container = vector<size_t>,
		 typename nxt_container = vector<size_t>,
		 typename data_container = vector<T_value>,
		 typename index_type = size_t>
struct basic_fs {
	// front star, without initialization
	data_container data;
	nxt_container nxt;
	head_container head;
	index_type cnt;
	basic_fs() : cnt(0) {}
	struct data_t {
		T_key key;
		basic_fs* base;
		struct iterator {
			index_type pos;
			data_t* base;
			T_value &operator*() { return base->base->data[pos]; }
			iterator &operator++() { pos = base->base->nxt[pos]; return *this; }
			operator index_type&() { return pos; }
		};
		iterator end() { return {0, this}; }
		iterator begin() { return {base->head[key], this}; }
		void push_back(const T_value &value) {
			base->data[++base->cnt] = value;
			base->nxt[base->cnt] = base->head[key];
			base->head[key] = base->cnt;
		}
		bool empty() { return base->head[key] == 0; }
		size_t size() {
			size_t ans = 0;
			for (size_t i = base->head[key]; i; i = base->nxt[i]) {
				ans++;
			}
			return ans;
		}
		void clear() { base->head[key] = 0; }
		friend ostream &operator<<(ostream &os, const data_t &a) {
			os << "[";
			size_t i = a.base->head[a.key];
			while (i) {
				os << a.base->data[i];
				i = a.base->nxt[i];
				if (i) {
					os << ",";
				}
			}
			return os << "]";
		}
	};
	data_t operator[](const T_key &x) { return {x, this}; }
};
template<typename T,
		 size_t index_range,
		 size_t value_size = index_range>
using array_fs = basic_fs<size_t,
						  T,
						  int[index_range],
						  int[value_size],
						  T[value_size],
						  int>;
#define int long long
#if 1
using ll = long long;
using ull = unsigned long long;
using i8 = int8_t;
using u8 = uint8_t;
using i16 = int16_t;
using u16 = uint16_t;
using i32 = int32_t;
using u32 = uint32_t;
using i64 = int64_t;
using u64 = uint64_t;
using i128 = __int128_t;
using u128 = __uint128_t;
using pii = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vpii = vector<pii>;
using sti = set<int>;
using mpii = map<int, int>;
using usti = unordered_set<int>;
using umpii = unordered_map<int, int>;
using msti = multiset<int>;
using umsti = unordered_multiset<int>;
using sos = ostream;
using sis = istream;
using soss = ostringstream;
using siss = istringstream;
#endif
#define min(x, y) ((x) < (y) ? (x) : (y))
#define max(x, y) ((x) > (y) ? (x) : (y))
#define mmin(x, y) ((x) < (y) ? (x) : (y))
#define mmax(x, y) ((x) > (y) ? (x) : (y))
#define Cpre(x) mint fac[(x) + 5], inv[(x) + 5]; struct Cpre##x##_t { Cpre##x##_t() { build_factorial(x, fac, inv); } } Cpre##x;
#define lowbit(x) ((x) & -(x))
#define abs(x) ((x) < 0 ? -(x) : (x))
// #define swap(a,b) a ^= b ^= a ^= b
#define INF 1e18
#define bin(a,b) bitset<a>(b)
#define getbit(a, b) (((a) >> (b)) & 1)
#define cde(...) cout << debug(__VA_ARGS__) << endl
#define dmi << '-' <<
#define dpl << '+' <<
#define dmu << '*' <<
#define ddi << '/' <<
#define dor << '|' <<
#define dan << '&' <<
#define dxo << '^' <<
#define dno << '!' <<
#define dco << ',' <<
#define ddo << '.' <<
using fast_ios::ewin;
using fast_ios::ewout;
// #define cin ewin
// #define cout ewout
#define MAXN 100005
#define MAXM 200005
#define MAXQ 2005
#define K 500
int n, a[MAXN], m, s[MAXM], t[MAXM];
struct query_f_t {
	int x, y, k;
	query_f_t(int X = 0, int Y = 0, int _K = 0) : x(X), y(Y), k(_K) {}
} query_f[MAXM * 10];
int qf;
int q, b[MAXQ];
array_fs<int, MAXN, MAXN * 2> e;
int fa[MAXN], dfn[MAXN], id[MAXN * 2], stamp, dep[MAXN];
array_fs<tuple<int, int, int>, MAXN * 2, MAXM * 20> updates;
int g[MAXN];
int buc[MAXN];
int x[MAXQ];
int invb[MAXN * 2];
void dfs(int u, int fa) {
	::fa[u] = fa;
	dep[u] = dep[fa] + 1;
	id[dfn[u] = ++stamp] = u;
	for (int v : e[u]) {
		if (v == fa) continue;
		dfs(v, u);
	}
	id[++stamp] = -u;
}
void dfs_g(int u, int fa) {
	for (int v : e[u]) {
		if (v == fa) continue;
		dfs_g(v, u);
		g[u] += g[v];
	}
	if (invb[2 * a[u]]) {
		x[invb[2 * a[u]]] += g[u];
	}
}
namespace LCA {
	int anc[MAXN][20];
	void build() {
		for (int i = 1; i <= n; i++) {
			anc[i][0] = fa[i];
		}
		for (int j = 1; j < 20; j++) {
			for (int i = 1; i <= n; i++) {
				anc[i][j] = anc[anc[i][j - 1]][j - 1];
			}
		}
	}
	int LCA(int x, int y) {
		if (dep[x] < dep[y]) swap(x, y);
		for (int i = 19; ~i; i--) {
			if (dep[anc[x][i]] >= dep[y]) {
				x = anc[x][i];
			}
		}
		if (x == y) return x;
		for (int i = 19; ~i; i--) {
			if (anc[x][i] != anc[y][i]) {
				x = anc[x][i];
				y = anc[y][i];
			}
		}
		return fa[x];
	}
}
signed main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	for (int i = 1, u, v; i < n; i++) {
		cin >> u >> v;
		e[u].push_back(v);
		e[v].push_back(u);
	}
	cin >> m;
	for (int i = 1; i <= m; i++) {
		cin >> s[i] >> t[i];
	}
	cin >> q;
	for (int i = 1; i <= q; i++) {
		cin >> b[i];
		invb[b[i]] = i;
	}
	dfs(1, 0);
	LCA::build();
	for (int i = 1; i <= m; i++) {
		int a = LCA::LCA(s[i], t[i]);
		int x = s[i];
		int y = t[i];

		query_f[++qf] = {x, x, 1};
		query_f[++qf] = {x, fa[a], -2};
		query_f[++qf] = {fa[a], fa[a], 1};
		g[x]--;
		g[fa[a]]++;

		query_f[++qf] = {y, y, 1};
		query_f[++qf] = {y, a, -2};
		query_f[++qf] = {a, a, 1};
		g[y]--;
		g[a]++;

		query_f[++qf] = {x, y, 2};
		query_f[++qf] = {fa[a], y, -2};
		query_f[++qf] = {x, a, -2};
		query_f[++qf] = {fa[a], a, 2};
	}
	dfs_g(1, 0);
	for (int i = 1; i <= qf; i++) {
		query_f[i].x = dfn[query_f[i].x];
		query_f[i].y = dfn[query_f[i].y];
	}
	sort(query_f + 1, query_f + qf + 1, [](const query_f_t &a, const query_f_t &b)->bool {
		if (a.x / K == b.x / K) {
			return a.y < b.y;
		} else {
			return a.x / K < b.x / K;
		}
	});
	for (int i = qf - 1; i; i--) {
		query_f[i].k += query_f[i + 1].k;
	}
	int fi = 0, fj = 0;
	for (int i = 1; i <= qf; i++) {
		// cout << query_f[i].x spc query_f[i].y spc query_f[i].k << endl;
		if (fi < query_f[i].x) {
			updates[fj].push_back({fi + 1, query_f[i].x, query_f[i].k});
		} else if (fi > query_f[i].x) {
			updates[fj].push_back({query_f[i].x + 1, fi, -query_f[i].k});
		}
		fi = query_f[i].x;
		if (fj < query_f[i].y) {
			updates[fi].push_back({fj + 1, query_f[i].y, query_f[i].k});
		} else if (fj > query_f[i].y) {
			updates[fi].push_back({query_f[i].y + 1, fj, -query_f[i].k});
		}
		fj = query_f[i].y;
	}
	for (int i = 2 * n; i; i--) {
		for (tuple<int, int, int> &j : updates[i]) {
			for (int k = get<0>(j); k <= get<1>(j); k++) {
				buc[a[abs(id[k])]] += get<2>(j) * (id[k] > 0 ? 1 : -1);
			}
		}
		for (int j = 1; j <= q; j++) {
			if (a[abs(id[i])] <= b[j]) {
				x[j] += buc[b[j] - a[abs(id[i])]] * (id[i] > 0 ? 1 : -1);
			}
		}
	}
	for (int i = 1; i <= q; i++) {
		cout << x[i] / 2 << endl;
	}
	return 0;
}

感谢 GPT 2 负责部分代码编写。

感谢 GPT 5.5 负责全部调试工作。

原文
存档评论6 条抓取于