Codeforces 175 B

 

B. Find Marble
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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 sto 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.

Sample test(s)
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 <cstdio>
#include <cstring>

using namespace std;

int a[100005];
int b[100005];

int main()
{
    int n,s,t,tmp,ans=0,err=0;
    cin>>n>>s>>t;
    for(int i=1;i<=n;i++)
      cin>>a[i];
    tmp=s;
    while(t!=tmp)
    {
        if(b[tmp])
        {
            err=1;
            t++;
            cout
            break;
        }
        b[tmp]=1;
        tmp=a[tmp];
        ans++;
    }
    if(err)cout<<-1<<endl;
    else cout<<ans<<endl;
    return 0;
}

本文链接:Codeforces 175 B

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:Rexdf,谢谢!^^


此条目发表在ACM分类目录,贴了标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。

*

:zsmilebig: :zsadbig: :zwiredbig: :zgreenhappy: more »

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据