Find Marble

Find Marble
Petya and Vasya are playing a game. Petya’s got n non-transparent glasses, standing in a row. The glasses’ positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.

First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn’t travel from one glass to another: it moves together with the glass it was initially been put in.

After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya’s task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

Input
The first line contains three integers: n, s, t (1 ≤ n ≤ 105; 1 ≤ s, t ≤ n) — the number of glasses, the ball’s initial and final position. The second line contains n space-separated integers: p1, p2, …, pn (1 ≤ pi ≤ n) — the shuffling operation parameters. It is guaranteed that all pi’s are distinct.

Note that s can equal t.

Output
If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

Examples
Input
4 2 1
2 3 4 1
Output
3
Input
4 3 3
4 1 3 2
Output
0
Input
4 3 4
1 2 3 4
Output
-1
Input
3 1 3
2 1 3
Output
-1

注意下标和数组下标位置上表示的值就行了。

在这里插入代码片
#include"iostream"
#include"cstring"
#include"algorithm"
using namespace std;
int main()
{
	int a[100005];
	int s,t,n;
	while(cin >> n>>s>>t)
	{
		for(int i = 1;i <= n;i ++)
		{
			cin >> a[i];
		}
		if(s==t)
		{
			cout<<0<<endl;
			continue;
		}
		int vst[100005]={0};
		int cnt=0,pl=0;
		do
		{
			vst[s]=1;
			s=a[s];//这里就是重中之重
			cnt++;
			if(s==t)
			{
				cout<<cnt<<endl;
				pl=1;
				break;
			}
		///	cout<<s<<endl;
		}while(vst[s]==0);
		if(!pl)
		{
			cout<<-1<<endl;
		}
	}
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值