티스토리 뷰

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int N, K;
	int ans = 0;
	cin >> N >> K;
	
	vector<int> a(N);
	
	for (int i = 0; i < N; i++)
	{
		cin >> a[i];
	}
	int temp;
	vector<bool> vi(N);
	temp = a[0];
	while (vi[temp] != true)
	{
		ans++;
		vi[temp] = true;
		if (temp == K)
		{
			cout << ans  << endl;
			return 0;
		}
		temp = a[temp];
		
	}
	cout << "-1" << endl;
	
	return 0;


}

'알고리즘' 카테고리의 다른 글

C++ 백준 1439번 뒤집기  (0) 2022.07.12
C++ 백준 1436번 영화감독 숌  (0) 2022.07.10
C++ 백준 1049번 기타줄  (0) 2022.07.10
C++ 백준 1026번 보물  (0) 2022.07.10
C++ 백준 2839번 설탕 배달  (0) 2022.07.06
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함