AtCoder Beginner Contest 167 D - Teleporter (dfs)

题目链接:传送门

思路:题目提供了一个每个点有且仅有一条出边的有向图,所以一定能形成环,一条链上有且只会有一个环(可以证明),所以做法就是dfs一下,记录经过的路径,顺便记一下重复经过的点(这个点是一个环的开始),k最大1e18,此时一定是在环上移动,取模即可。

代码:

#include <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 + 5;

int a[maxn] , vis[maxn];
int ans , pos;
vector <int> v;

void dfs(int u) {
	ans++;
	vis[u] = ans;
	v.push_back(u);
	if(!vis[a[u]])dfs(a[u]);
	else {
		pos = vis[a[u]];
		v.push_back(a[u]);
		return;
	} 
}

int main() {
	int n ;
	long long k;
	ios::sync_with_stdio(0);
	cin >> n >> k;
	for(int i = 1 ; i <= n ; i++)cin >> a[i];
	dfs(1);
	if(k < v.size()) {
		cout << v[k] << "\n";
	}
	else {
		k -= v.size();
		int len = v.size() - pos;
		cout << v[pos +  k % len] << "\n"; 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39475280/article/details/106043460
今日推荐