跳到正文

个人记录

P4600

nick_zha约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年3月27日
更新
2026年3月27日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1
C++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
int n, m;
char s[N];
vector<int> pos[N];
ll hsh[N];
namespace ACAM {
	struct Node {
		int son[26], fail, dep;
		bool end;
		void init() {
			memset(son, 0, sizeof(son));
			fail = dep = 0;
			end = false;
		}
	} tr[N];
	int tot;
	int fa[N];
	vector<int> g[N];
	int sz[N], hson[N], top[N], dep[N];
	void init() {
		tot = 0;
		tr[0].init();
		hsh[0] = 0;
		for (int i = 0; i < N; i++) g[i].clear();
	}
	void insert(char s[], int id) {
		int u = 0;
		pos[id].clear();
		pos[id].push_back(0);
		for (int i = 0; s[i]; i++) {
			int ch = s[i] - 'a';
			if (!tr[u].son[ch]) {
				tr[++tot].init();
				tr[tot].dep = tr[u].dep + 1;
				hsh[tot] = (hsh[u] * 26 + ch) % mod;
				tr[u].son[ch] = tot;
			}
			u = tr[u].son[ch];
			tr[u].end = true;
			pos[id].push_back(u);
		}
	}
	void build() {
		queue<int> q;
		for (int i = 0; i < 26; i++) {
			if (tr[0].son[i]) {
				int v = tr[0].son[i];
				q.push(v);
				fa[v] = tr[v].fail;
				g[tr[v].fail].push_back(v);
			}
		}
		while (!q.empty()) {
			int u = q.front();
			q.pop();
			for (int i = 0; i < 26; i++) {
				if (tr[u].son[i]) {
					int v = tr[u].son[i];
					tr[v].fail = tr[tr[u].fail].son[i];
					fa[v] = tr[v].fail;
					g[tr[v].fail].push_back(v);
					q.push(v);
				} else {
					tr[u].son[i] = tr[tr[u].fail].son[i];
				}
			}
		}
		dep[0] = 0;
		stack<pair<int, int>> st;
		st.push({0, 0});
		while (!st.empty()) {
			auto [u, state] = st.top(); st.pop();
			if (state == 0) {
				st.push({u, 1});
				for (int v : g[u]) {
					dep[v] = dep[u] + 1;
					st.push({v, 0});
				}
			} else {
				sz[u] = 1;
				hson[u] = -1;
				for (int v : g[u]) {
					sz[u] += sz[v];
					if (hson[u] == -1 || sz[v] > sz[hson[u]]) hson[u] = v;
				}
			}
		}
		stack<pair<int, int>> st2;
		st2.push({0, 0});
		while (!st2.empty()) {
			auto [u, tp] = st2.top(); st2.pop();
			top[u] = tp;
			if (hson[u] != -1) {
				st2.push({hson[u], tp});
			}
			for (int v : g[u]) {
				if (v != hson[u]) {
					st2.push({v, v});
				}
			}
		}
	}
	int lca(int u, int v) {
		while (top[u] != top[v]) {
			if (dep[top[u]] < dep[top[v]]) swap(u, v);
			u = fa[top[u]];
		}
		return dep[u] < dep[v] ? u : v;
	}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	ACAM::init();
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%s", s);
		ACAM::insert(s, i);
	}
	ACAM::build();
	scanf("%d", &m);
	while (m--) {
		int i, j, k, l;
		scanf("%d%d%d%d", &i, &j, &k, &l);
		int u = pos[i][j];
		int v = pos[k][l];
		ll ans = hsh[ACAM::lca(u, v)];
		printf("%lld\n", ans);
	}
	return 0;
}
原文