跳到正文

题解

题解:P5557 旅行

NyaingCBC约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月11日
篇幅
约 4 分钟
题目
P5557

版本

  1. v1当前

思路分析

一眼倍增,但是有一些细节需要仔细处理一下。

首先对于一个内向基环树森林,跳 nn 次一定能够跳到环里。所以,如果次数不够就直接倍增跳,够的话另说。

在这里判断的时候,一定要注意如果 t1=1t_1=1 的话,那么次数一定是够的,其余的情况暴力乘着判断才是 O(log⁡)O(\log) 的。

我们还需要处理出每一个环的环长。将剩余次数进行取模之后再倍增着跳。

这里要注意不要忘了减前面已经跳过的 nn 次。

然后就没有什么难点了。代码如下:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, a[400005][20], m;
inline int qpow(long long a, int b, int p) {
	long long ret = 1;
	for (; b; b >>= 1, a = a * a % p)
		(b & 1) && (ret = ret * a % p);
	return ret;
}
int vis[400005], rl[400005]; stack<int>s;
inline void dfs(int p, int t) {
	vis[p] = t; s.emplace(p);
	if (vis[a[p][0]] == t) {
		for (int i = a[p][0]; i != p; i = a[i][0])
			rl[a[p][0]]++;
		rl[a[p][0]]++;
		while (s.top() != a[p][0])
			rl[s.top()] = rl[a[p][0]], s.pop();
		s.pop(); return;
	}
	if (vis[a[p][0]]) rl[p] = rl[a[p][0]], s.pop();
	else if (dfs(a[p][0], t), !rl[p]) 
		rl[p] = rl[a[p][0]], s.pop();
}
inline bool cmp(int t1, int t2, int wt) {
	long long ap = 1; if (t1 == 1) return 1;
	for (int i = 1; i <= t2; ++i)
		if ((ap *= t1) > wt) return 0;
	return 1;
}
signed main() {
	ios::sync_with_stdio(0); cin >> n;
	for (int i = 1; i <= n; ++i) cin >> a[i][0];
	for (int j = 1; j <= 19; ++j)
		for (int i = 1; i <= n; ++i)
			a[i][j] = a[a[i][j - 1]][j - 1];
	for (int i = 1; i <= n; ++i) if (!rl[i]) dfs(i, i);
	cin >> m;
	for (int i = 1, s, t1, t2; i <= m; ++i) {
		cin >> s >> t1 >> t2; 
		if (cmp(t1, t2, n)) {
			t1 = qpow(t1, t2, n + 1);
			for (int j = 19; j >= 0; j--)
				if (t1 >> j & 1) s = a[s][j];
			cout << s << endl; continue;
		}
		for (int j = 19; j >= 0; j--)
			if (n >> j & 1) s = a[s][j];
		t1 = qpow(t1, t2, rl[s]);
		t1 = (t1 - n % rl[s] + rl[s]) % rl[s];
		for (int j = 19; j >= 0; j--)
			if (t1 >> j & 1) s = a[s][j];
		cout << s << endl;
	}
}
原文