萌新求助
查看原帖
萌新求助
434929
Usada_Pekora楼主2022/9/17 13:52

以下是两种 Query 的写法。

inline node Query(int u, int v) {
	tp[0] = tp[1] = 0;
	int cur = 0;
	while (top[u] != top[v]) {
		if (dep[top[u]] < dep[top[v]]) {
			swap(u, v);
			cur ^= 1;
		}
		s[cur][++tp[cur]] = query(1, 1, n, dfn[top[u]], dfn[u]);
		u = fa[top[u]];
	}
	if (dep[u] > dep[v]) {
		swap(u, v);
		cur ^= 1;
	}
	s[cur][++tp[cur]] = query(1, 1, n, dfn[u], dfn[v]);
	node res(0, 0, 0);
	if (tp[0] == 0) {
		for (int i = tp[1]; i >= 1; i--)
			res = res + s[1][i];
	} else {
		res = s[0][1];
		for (int i = 2; i <= tp[0]; i++)
			res = res + s[0][i];
		for (int i = tp[1]; i >= 1; i--)
			res = res + s[1][i];
	}
	return res;
}
inline int Query(int u, int v) {
	int res = 0;
	int pos1 = 0,  pos2 = 0, lc = 0, rc = 0;
	while (top[u] != top[v]) {
		if (dep[top[u]] < dep[top[v]]) swap(u, v), swap(pos1, pos2);
		node o = query(1, 1, n, dfn[top[u]], dfn[u]);
		lc = o.lc, rc = o.rc, res += o.sm;
		if (rc == pos1) res--;
		pos1 = lc, u = fa[top[u]];
	}
	if (dfn[u] > dfn[v]) swap(u, v), swap(pos1, pos2);
	node o = query(1, 1, n, dfn[u], dfn[v]);
	lc = o.lc, rc = o.rc, res += o.sm;
	if (lc == pos1) res--;
	if (rc == pos2) res--;
	return res;
}

感觉思路大致相同,为啥第一种只过了 hack 和样例呢?

2022/9/17 13:52
加载中...